您可以在新添加的 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
已贬值。我没有调查它,但它被称为MutationOvserver
:https ://developer.mozilla.org/en-US/docs/Web/API/MutationObserver