您可以将新添加的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/
UPDATE
有一个新的API THI s为DOMNodeInserted
此时折旧。我还没有看过,但它被称为MutationOvserver
:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
*在所有浏览器中,加载事件不会冒泡。在Internet Explorer 8及更低版本中,粘贴和重置事件不会冒泡。这些事件不支持与委派一起使用,但可以在事件处理程序直接附加到生成事件的元素时使用。*(http://api.jquery.com/on/)现在,关于如何解决这个问题... – Corbin 2012-03-07 22:52:14
这是一个问题,以消除'负载'功能,你正试图完成所有的一切,而是操作后,项目已附加'链'的HTML? $('#container')。append('
@Ohgodwhy不是我无法想出一个解决方法(对于这个愚蠢的例子更是如此),我只想知道是否有一个我错过的事件可以用于我的目的描述。 – 2012-03-07 22:55:37