您可以在新添加的 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/ http://jsfiddle.net/ggHh7/4/
即使您通过不同的方法加载动态内容,此方法也允许您在全局范围内执行某些操作。
Update
我不确定浏览器支持(我假设 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/ http://jsfiddle.net/ggHh7/7/
UPDATE
为此有一个新的 API:DOMNodeInserted
此时已贬值。我还没研究过,但它叫MutationOvserver
: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver