你好,
编辑:正如你们大多数人所建议的那样,我尝试使用 .on()
而不是 .live()
。但它没有帮助。这个问题不仅使用 ajax 调用,甚至尝试使用 jquery 添加新元素,事件也没有注册到新创建的元素。
我在下面更改了我的脚本。
如果在现有表上触发点击事件,我将添加新表。点击事件对第一个表触发良好,但对下一个新添加的表不触发脚本。
我认为问题在于 .each()
。这个功能对新添加的元素不起作用,请问有什么办法可以解决这个问题吗?
我有一个 html 页面,其中的内容由 ajax 事件更改。我想将点击事件注册到我的页面包含的所有表格。第一次它工作正常但是一旦内容被 ajax 更改,事件就会被触发..
HTML:
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
</head>
<style>
table{
border-collapse:collapse;
}
table td{
border:1px solid;
}
</style>
<body>
<table clk="true">
<thead>
<tr>
<td>S.No</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr><td>1</td> <td>Rama Rao</td></tr>
<tr><td>2</td> <td>Tom Cruise</td></tr>
<tr><td>3</td> <td>Tom Honks</td></tr>
<tr><td>4</td> <td>Will Smith</td></tr>
</tbody>
</table>
</body>
脚本:
$('table').each(function(){
if($(this).attr('clk')=="true"){
$(this).find('tbody tr td').live('click',function(){
var str= $('table').html();
str = '<table clk="true">'+str+'</table>';
$('table').after(str);
});
}
});
注意:如果表只有属性 clk="true",则应注册事件。检查我认为 "each" 循环是必需的。
感谢任何帮助。
最佳答案
关于javascript - 没有为 Ajax 添加的新元素注册 Jquery 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12075389/