我有一个 HTML 表格,单击表格单元格时会打开一个弹出窗口,并在该表格中添加新的表格行。我也想向这些行添加 .click() 监听器。这是我的 HTML 表格
<table id="myTable" style="width: 100%;">
<tr><th></th><th>Kompetence</th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th></tr>
<tr style=><td rowspan="2">My text</td>
<td>Some text</td><td class="hodnoceni 1"> </td><td class="hodnoceni 2"> </td><td class="hodnoceni 3"> </td><td class="hodnoceni 4"> </td><td class="hodnoceni 5"> </td><td class="hodnoceni 6"> </td></tr>
<tr><td>Another text</td><td class="hodnoceni 1" title="sum titl"> </td><td class="hodnoceni 2"> </td><td class="hodnoceni 3"> </td><td class="hodnoceni 4"> </td><td class="hodnoceni 5"> </td><td class="hodnoceni 6"> </td></tr>
<tr class="newPartOfTable"><td rowspan="50">This is new part of table</td><td id="testId" class="testClass"> </td><td class="hodnoceni 1"> </td><td class="hodnoceni 2"> </td><td class="hodnoceni 3"> </td><td class="hodnoceni 4"> </td><td class="hodnoceni 5"> </td><td class="hodnoceni 6"> </td></tr>
</table>
这是我的 JavaScript
var possibleInputs = ["T", "A", "Ž", " "];
var curValue;
$("#myTable .hodnoceni").click(function() {
var level;
var index = 0;
var rowIndex = $(this).parent().index();
curValue = $(this).text();
if(curValue == "T"){
index = 1;
}else if(curValue == "A"){
index = 2;
}else if(curValue == "Ž"){
index = 3;
}else{
index = 0;
}
console.log("row index");
console.log("total rows"+$("#kompetence tr").length);
console.log("td clicked");
var num = $(this).attr("class").match(/\d+/);
$(this).text(possibleInputs[index]);
console.log("Hodnoceni: "+num);
});
$(".newPartOfTable").click(function(){
var rows = $("#kompetence tr").length;
window.open("newPage.html?rows="+rows, "New popup", "width=600,height=300");
});
这是向表中添加新行的 JavaScript(在弹出窗口中)
var table = window.opener.document.getElementById("myTable");
console.log(table);
var row = tabulka.insertRow(<%=paramTableRows %>);
for(var i = 0; i < 7; i++){
var cell = row.insertCell(i);
cell.innerHTML = "<%= paramTableRows %>";
cell.className = "hodnoceni";
}
我想要做的是在向表中添加新行后,我希望它们将现有的 .click() 函数绑定(bind)到它们。
感谢您的帮助。
最佳答案
使用.on()
由于 javascript 添加的新元素在 DOM 就绪或页面加载时不是 DOM 的一部分,因此您必须使用 Event Delegation
$(document).on("click", "#myTable .hodnoceni", function() {
或
$("#myTable").on("click", ".hodnoceni", function() {
关于javascript - 刷新父窗口中的 jquery .click 监听器以使用新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19557697/