如何在表行上执行函数,请单击javascript/html



我已经建立了一个返回Ajax结果的表,如下所示:

function searchUsers() {
var searchText = (document.getElementById('searchInput').value)
$.ajax({
url : "https:" + "/" + "/downstreamaudio.com/SearchUsers.php",
method : 'POST',
data : {searchQuery: searchText},
dataType: "json",
success : function a(result) {
console.log(result)
console.log(result.length)
var i;
var table = document.getElementById("userSearchTableId");
table.style.height = (result.length * 80 + "px")
while(table.rows.length > 0) {
table.deleteRow(0);
}
table.style.border = "0px solid black"
for (i = 0; i < result.length; i++) {
console.log(result[i].username);
document.querySelector('.userSearchTable').style.opacity = "100"
var username = result[i].username;
table.style.border = "4px solid black"
table.style.borderCollapse = "seperate"
var row = table.insertRow(0);
row.onclick = cellClicked("Test");
var cell1 = row.insertCell(0);
cell1.style.width = "80px"
cell1.style.height = "50px"
cell1.setAttribute("class", "UserImage")
var image = document.createElement("img");
image.height = "50"
image.width = "50"
image.style.backgroundColor = "green"
image.style.margin = "15px 15px 15px 12px"
image.style.padding = "0px 0px 0px 0px"
image.style.borderRadius = "25px"
image.style.borderColor = "black"
image.style.border = "2px solid black"
cell1.appendChild(image)
var cell2 = row.insertCell(1);
cell2.style.fontSize = "20"
cell2.style.fontFamily = "Arial, Helvetica, sans-serif"
cell2.style.fontWeight = "Semi Bold"
cell2.innerHTML = username

}
error : function b(jqxhr, status, exception) {
alert(status);
}
}
})

是否可以使一行可点击,从而调用onclick函数?我已经尝试将.onclick添加到该行,但没有成功。我还需要知道点击了哪一行,因为我需要该行单元格的innerHTML。

假设您的表是在页面加载后编写或创建的,则需要事件委派。在document上设置点击监听器,然后测试tagName,看看你是否在TD上。

document.addEventListener('click', function(e) {
if (e.target.tagName.toLowerCase() === "td") {
let tr = e.target.closest('tr');
console.log('found td tag with this contents: ', e.target.innerHTML)
console.log('found tr tag with this contents: ', tr.innerHTML)
} else {
console.log('not a table cell', e.target.tagName)
}
})
setTimeout(function() {
document.querySelector('#content').innerHTML += "<table><tr><td>or me</td><td>or me too</td></tr></table>"
}, 1000);
<div id="content">
<div>try clicking me</div>
</div>

最新更新