Here jsFiddle to test sample自定義事件文檔onContentChange
我目前正在寫一個jQuery代碼段來處理DOM的任何HTML內容的改變「觸發」任何的jQuery domManip功能(擴展一些功能)。不知道這是做這件事的最佳方式,所以任何建議都會受到歡迎。 如果綁定到文檔,此代碼段按預期工作。但是,如果我嘗試將其綁定到特定元素,我正面臨着一些功能如.remove()的問題。也許這是由於自定義事件不使用正常的傳播行爲,但我真的不確定。
這是一個工作示例中,我結合「contentChange」事件記錄,工程跨瀏覽器作爲我可以測試:{火狐,IE9,Chrome和Safari Win7的下}
;
(function ($) {
$.fn.contentChange = function (types, data, fn) {
return this.on('contentChange', types, null, data, fn);
};
var oDomManip = $.fn.domManip,
oHtml = $.fn.html,
oEmpty = $.fn.empty,
oRemove = $.fn.remove,
extendFct = function (oFct, sender, args) {
return oFct.apply(sender, args), $.event.trigger('contentChange');
//=>if testing specific element (#test) use instead following line
//return oFct.apply(sender, args), $(sender).trigger('contentChange');
};
$.fn.domManip = function() {
extendFct(oDomManip, this, arguments)
};
$.fn.html = function() {
extendFct(oHtml, this, arguments)
};
$.fn.empty = function() {
extendFct(oEmpty, this, arguments)
};
$.fn.remove = function() {
extendFct(oRemove, this, arguments)
};
})(jQuery);
使用: $.event.trigger('contentChange')
觸發自定義事件。
調用喜歡它:
$(document).contentChange(function() {
console.log("onContentChange")
});
但是,如果我使用:
$('#test').contentChange(function() {
console.log("onContentChange")
});
自定義事件不會被觸發。 因此,一個特定的元素上觸發一個自定義事件,我可以引發這樣的:
$(sender).trigger('contentChange');
但現在,打電話給自我或兒童remove()
方法不觸發我的自定義事件。 我可以理解,如果我刪除元素,則不會調用事件回調函數,但爲什麼在刪除子元素時它不會調用它(如果它綁定到文檔,它會工作)?
我期待此行進行自定義事件冒泡爲「#TEST」:
$('#test').find('div:first').remove();
有什麼辦法來觸發綁定到特定的元素這個自定義事件操縱這個元素和時/或其子女?
不應'$ .event.trigger( 'contentChange')'來代替上觸發事件元件?如被操縱的那個?側記,這是livequery用來獲得類似效果的技術,我建議查看livequery是如何實現可能的改進的。 – 2013-04-10 14:13:55
爲什麼你不使用[DOMSubtreeModified](http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener) – alexP 2013-04-10 14:21:32
@alexP http://stackoverflow.com/questions/ 6659662 /爲什麼這是domsubtree修改事件棄用在DOM級別3 – 2013-04-10 14:24:26