2011-01-05 56 views
1

說我想製作一個名爲'alertMeOnRemove'的小插件,這是一個不言自明的插件。我希望它只是覆蓋調用它的元素的remove()函數。DOM元素特定功能覆蓋或功能

$('a').alertMeOnRemove(); 
$('div').remove(); // no alert 
$('a.subset-of-a').remove(); //alert 
$('a').remove() //alert 

我知道一般重寫jQuery函數是既可能又簡單。這可能嗎?

回答

2

是啊,這並不困難。

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

    $.fn.alertMeOnRemove = function(){ 
     this.each(function(){ 
      $.data(this, 'alertMeOnRemove', true); 
     }); 
    }; 

    $.fn.remove = function(){ 
     this.each(function(){ 
      if ($.data(this, 'alertMeOnRemove')) { 
       alert('removing item'); 
      } 
     }); 

     _remove.call(this); 
    }; 
})(); 
+0

非常好!這正是我所期待的。沒有完全按照你的要求工作,但是......'_remove.call(this);'必須在'.each()' – smdrager 2011-01-05 14:46:54

+0

以外。 – lonesomeday 2011-01-05 15:57:22

0

我真的不知道,如果我得到你,但你可以做到這一點,如:

var _oldRemove = $.fn.remove; 
$.fn.remove = function() { 
    if(/* some condition */) 
     alert('foobar'); 

    _oldRemove.apply(this, arguments); 
};