我有这样的 HTML 代码
<table id="Table1">
<tbody>
<tr>
<th scope="col">
Srno.
</th>
<th scope="col">
Emp code
</th>
<th scope="col">
Name
</th>
<th scope="col">
Mobile No
</th>
<th scope="col">
Delete
</th>
</tr>
</tbody>
</table>
我有一个按钮,当单击按钮
时,新的tr
将4个td
添加到表中,代码变成这样.
<table id="Table1">
<tbody>
<tr>
<th scope="col">
Srno.
</th>
<th scope="col">
Emp code
</th>
<th scope="col">
Name
</th>
<th scope="col">
Mobile No
</th>
<th scope="col">
Delete
</th>
</tr>
<tr>
<td>
1
</td>
<td style="display: none;">
198
</td>
<td>
SHR003
</td>
<td>
Saurabh khandelwal
</td>
<td>
9891491920
</td>
<td>
<img class="clsImage" src="../../images/delete1.png" style="cursor: pointer;">
</td>
</tr>
</tbody>
</table>
现在我使用delete
图像来删除在iframe
中动态
添加的当前行。同样我使用Jquery
代码:
$("iframe").contents().find('body').on("click", '.clsImage', function (e) {
alert('111');
});
但是点击删除
图像按钮后,iframe内最新添加的tr
不会给出警报
。
我正在使用“Jquery 1.9.1”
请帮助我
最佳答案
也许问题在于您试图在完成加载之前将 click
事件绑定(bind)到 iframe
内的元素。您可以尝试在 iframe 加载后绑定(bind)事件处理程序:
$('iframe').load(function () {
$(this).contents().find('body').on('click', '.clsImage', function () {
alert('111');
});
});
编辑:这是我的意思的一个简单例子。您需要给足够的时间让iframe
构建自己的DOM,然后才能注册任何处理程序。
这是index.html的内容:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function() {
$('iframe').load(function () {
$(this).contents().find('body').on('click', '.clsImage', function () {
alert('111');
});
});
$('button').click(function () {
var $table = $('iframe').contents().find('table');
$table.append('<tr><td>1</td><td style="display: none">198</td><td>SHR003</td><td>Saurabh khandelwal</td><td>9891491920</td><td><img class="clsImage" src="../../images/delete1.png" style="cursor: pointer;"></td></tr>');
});
});
</script>
</head>
<body>
<button>add</button>
<iframe src="table.html"></iframe>
</body>
</html>
这是table.html的内容:
<table id="Table1">
<tbody>
<tr>
<th scope="col">
Srno.
</th>
<th scope="col">
Emp code
</th>
<th scope="col">
Name
</th>
<th scope="col">
Mobile No
</th>
<th scope="col">
Delete
</th>
</tr>
</tbody>
</table>
关于javascript - 如何在 iframe 内动态创建的表格元素上添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174959/