我有一个表,它是根据 SQL 查询中的数据通过 JavaScript 动态生成的。第一个单元格包含一个按钮,该按钮应检索该行 onclick 中第二个单元格中的值。出于某种原因,jQuery onclick 事件没有触发。浏览器中没有抛出任何错误。
HTML
...
for (var i=0; i<queryReturned.Result.length; i++) {
var tableRow = document.createElement("tr");
var cell = document.createElement("td");
var button = document.createElement("button"); //Button gets added here
button.type = "button";
button.value = "Remove Alert";
button.className = "buttonSelect"
cell.appendChild(button);
tableRow.appendChild(cell);
//This loop creates the rest of the cells and fills in their data
for (var j=0; j<Object.keys(queryReturned.Result[i]).length; j++) {
var cell2 = document.createElement("td");
var cellText = document.createTextNode(Object.values(queryReturned.Result[i])[j]);
cell2.appendChild(cellText);
tableRow.appendChild(cell2);
}
tableBody.appendChild(tableRow);
}
table.appendChild(tableBody);
table.setAttribute("border", "2");
body.appendChild(table);
...
jQuery
$(document).ready(function(){
$(".buttonSelect").on('click',function(){
var currentRow=$(this).closest("tr");
var col2=currentRow.find("td:eq(1)").html();
alert(col2); //alert for now to test if we grabbed the data
});
});
最佳答案
像这样改写你的事件处理函数:
$(document).on('click', '.buttonSelect', function(){ ... });
所以它也适用于动态添加的元素。
让我们知道进展如何!
关于javascript - 从动态生成的表中的单元格获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40951671/