2011-10-03 122 views
4

在某些函數中我刪除了像這樣的元素$('#'+id+' img.load').remove();,我如何跟蹤這個事件並運行自定義代碼?JQuery事件跟蹤

回答

5
(function($){ 
    var remove_orig = $.fn.remove; 

    $.fn.remove = function(){ 
    console.log('Remove called'); 
    remove_orig.apply(this, arguments); 
    }; 
})(jQuery); 

你可以在任何jQuery函數「鉤子」和內把你自己的處理代碼(包括測井方法(S))將執行之前執行本地jQuery代碼

demo(另一個版本與selector shown


捕捉去除是容易使用上述過載。簡單地改變鉤火之前(或之後)觸發jQuery的獲得它:

(function($){ 
    var remove_orig = $.fn.remove; 

    $.fn.remove = function(){ 
    this.trigger('removing'); 
    remove_orig.apply(this, arguments); 
    }; 
})(jQuery); 

$('#foo').bind('removing',function(e){ 
    alert('#foo is being removed'); 
}); 

$('#foo').remove(); 
+0

哇。這是很好的解決方案。 – genesis

+0

但我怎樣才能檢查什麼元素被刪除?因爲如果我理解正確,這段代碼在每次刪除任何元素時運行。 – Yekver

+0

@Yekver在新函數中迭代它們 - '$(this).each(...)' – Alnitak

3

一種方式是「觸發」自定義事件(在這個例子中,我使用的是Window):

$('#'+id+' img.load').remove(); 
$(window).trigger("MyElementRemoved", [id]); 

然後在你的代碼的另一部分「處理」事件:

$(window).bind("MyElementRemoved", function(e, elementId) { 
    alert("element removed: " + elementId); 
}