jQuery监听器不“监听”到动态创建的DOM元素的事件 [英] jQuery listener doesn't "listen" to events on DOM elements dynamically created

查看:1027
本文介绍了jQuery监听器不“监听”到动态创建的DOM元素的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的监听器:

$('.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?

推荐答案

在绑定事件处理程序时存在。如果您想让它监听动态创建的元素,您可以使用 live()函数使用当前和未来的元素。

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,推荐的方式是使用。on()函数替换 .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元素的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆