您可以將新添加的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