我有一个通过JavaScript基于SQL查询中的数据动态生成的表格。第一个单元格包含一个按钮,该按钮应检索该行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(){...});'动态添加元素。 (我不是100%确定'$(this)'是否与你的版本相同。) – connexo
Thanks @connexo。那就是诀窍。你应该完全补充说,作为答案,我可以给你应有的信用! –