单击动态创建的表上的函数
本文关键字:函数 单击 创建 动态 | 更新日期: 2023-09-27 18:32:29
>我有一个表,它是动态创建的。当我单击图像时,我需要删除表格行。在这里,单击功能不起作用。
动态创建的表。
row.append($("<td id="imageclose"><p>" + '<img src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" />' + "</p></td>"));
点击功能
$("#imgclose").click(function () {
alert("asdfg");
});
使用类imageclose
而不是像下面这样id
。因为id
对于每个元素都应该是唯一的。
row.append($("<td class="imageclose"><p>" + '<img src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" />' + "</p></td>"));
您需要动态生成的元素的事件委派。
$('body').on('click', '.imgclose img', function () {
$(this).closest('tr').remove();
});
你不能使用"ID",因为它应该是唯一的。因此,与其使用ID使用类来完成您的任务。
第一种方式onclick
调用函数。
row.append($("<td><p>" + '<img src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" onclick="abc()" />' + "</p></td>"));
function abc() {
$(this).closest('tr').remove();
}
具有类属性的第二种方式。
row.append($("<td><p>" + '<img class="myclass" src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" />' + "</p></td>"));
$('#tableId').on('click', '.myclass', function () {
$(this).closest('tr').remove();
});