38

我正在尝试对动态添加到页面上某个容器的元素进行一些条件操作,但我错过了一个事件。

假设我有一个容器:

<div id="container"></div>

我可以轻松地将事件处理程序绑定到所有新元素的单击函数,使用

$('#container').on('click', '.sub-element', function() { ... });

但是当元素添加到#container. 我试图绑定readyload无济于事。有什么办法可以做到这一点,还是我必须想出另一个解决方案来解决我的问题?

这个小提琴包含我的非工作示例

4

2 回答 2

42

您可以在新添加的 DOM 元素上触发自定义事件,该事件可由 jQuery 事件处理程序获取:

//bind to our custom event for the `.sub-element` elements
$('#container').on('custom-update', '.sub-element', function(){
    $(this).html('<b>yaay!</b>');
});

//append a new element to the container,
//then select it, based on the knowledge that it is the last child of the container element,
//and then trigger our custom event on the element
$('#container').append('<div class="sub-element">No worky!</div>').children().last().trigger('custom-update');

这是一个演示:http: //jsfiddle.net/ggHh7/4/

即使您通过不同的方法加载动态内容,此方法也允许您全局执行某些操作。

更新

我不确定浏览器是否支持(我假设 IE8 和更早版本不支持此功能)但您可以使用DOMNodeInserted突变事件来检测何时添加 DOM 元素:

$('#container').on('DOMNodeInserted', '.sub-element', function(){
    $(this).html('<b>yaay!</b>');
})

$('#container').append('<div class="sub-element">No worky!</div>');

这是一个演示: http: //jsfiddle.net/ggHh7/7/ ​</p>

更新

有一个新的 API,因为此时DOMNodeInserted已贬值。我没有调查它,但它被称为MutationOvserverhttps ://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

于 2012-03-07T22:55:18.713 回答
10

阅读上述答案后,我现在成功使用它:

$('body').on({
   DOMNodeInserted : function(){
      alert('I have been added dynamically');
   },
   click : function(){
      alert('I was clicked');
   },
   '.dynamicElements'
});

现在我所有的dynamicElements东西都可以在加载时做,利用很棒的.on()事件地图。

于 2013-03-03T01:16:47.270 回答