Javascript 单击JS中动态创建的表元素上的事件
我的页面上有一个按钮,单击它会显示一个动态创建的表。这是在JS文件中发生的。 表创建的一部分如下所示-Javascript 单击JS中动态创建的表元素上的事件,javascript,jquery,Javascript,Jquery,我的页面上有一个按钮,单击它会显示一个动态创建的表。这是在JS文件中发生的。 表创建的一部分如下所示- table_body = '<table border="1">'; table_body += '<tr>'; table_body += '<th>'; table_body += ''; table_body += '</th>'; table_body += '<
table_body = '<table border="1">';
table_body += '<tr>';
table_body += '<th>';
table_body += '';
table_body += '</th>';
table_body += '<th>';
table_body += 'Name';
table_body += '</th>';
table_body += '<th>';
table_body += 'Age';
table_body += '</th>';
table_body += '</tr>';
for(var i=0;i<number_of_rows;i++){
table_body+='<tr>';
table_body += '<td>';
table_body += i+1;
table_body += '</td>';
table_body += '<td>';
table_body += name[i];
table_body += '</td>';
table_body += '<td>';
table_body += '<a href="" id='+name[i]+'>Age Action</a>';
table_body += '</td>';
table_body+='</tr>';
}
table_body+='</table>';
document.getElementById("tableDiv").innerHTML = table_body;
id=第一个年龄动作行中的55。
是因为它是动态生成的吗?我已经添加了id属性,该属性对于它的不同行应该是不同的,但是当我单击其中任何一行时,它并没有记录我单击时的控制台消息
我还检查了页面源代码,它没有显示表中的任何元素。如何/在何处跟踪对元素的任何单击?任何帮助都将不胜感激。您使用的选择器与年龄操作链接元素不匹配 尝试更改此行:
<a href="" id='+name[i]+'>Age Action</a>
document.getElementById("tableDiv").innerHTML = table_body;
jQuery("#55").click(newTestFunction); //I have a console.log in newTestFunction
需要注意的一些事项:
- 元素id不能以有效HTML中的数字开头
- 此语法:
实际上是名为“name”的数组变量的索引name[i]
<a href="" id='+name[i]+'>Age Action</a>
document.getElementById("tableDiv").innerHTML = table_body;
jQuery("#55").click(newTestFunction); //I have a console.log in newTestFunction
这样,当您将事件添加到“#55”元素时,它将存在。您需要使用事件委派(即
on()
)来处理动态内容。此外,您不应该将原生JS与JQuery混合在一起,我一开始就把它放在了最上面。谢谢,这很有效。谢谢你的有用评论。
document.getElementById("tableDiv").innerHTML = table_body;
jQuery("#55").click(newTestFunction); //I have a console.log in newTestFunction