问题描述
我有这样的监听器:
$('.delete').click(function() {
...some stuff
});
此外,在同一页面上,另一个脚本以这种方式动态地向DOM添加元素: p>
Also, on the same page, another script dynamically add elements to the DOM in this way:
$('#list').append('<tr><td><a class="delete" href="#">delete</a></td></tr>');
我的问题是监听器没有侦听这些动态创建的元素。
My problem is that the listener doesn't "listen" to these dynamically created elements.
任何人都可以散发一些光吗?
Can anyone shed some light please?
推荐答案
在绑定事件处理程序时存在。如果您想让它监听动态创建的元素,您可以使用函数使用当前和未来的元素。
It will listen only on elements that existed when you bound the event handler. If you want it to listen to dynamically created elements you want to use the live() function, which works with current and future elements.
编辑:从jQuery 1.7,推荐的方式是使用函数替换 .bind()
, .live )
和 .delegate()
提供所有附加事件处理程序所需的功能。
as of jQuery 1.7, the recommended way is to use the .on() function, which replaces .bind()
, .live()
and .delegate()
by providing all functionality required for attaching event handlers.
这篇关于jQuery监听器不“监听”到动态创建的DOM元素的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!