2011-03-16 28 views
2

我想弄清楚如何包裝點擊事件。例如,這是我想要的代碼。將現有的jquery事件與默認設置相結合

$("#test").aclick(function() { 
    alert('hi'); 
}); 

aclick做的唯一事情就是自動使用e.preventDefault。 這是什麼東西?

$.fn.aclick = function(e) { 
    e.preventDefault(); 
    return $.fn.click.apply(this, arguments); 
}); 

謝謝。

回答

1

綁定處理程序時,事件對象e尚不存在。您需要創建一個默認的事件處理程序調用提供一個:

$.fn.aclick = function (handler) { 
    return this.each(function() { 
     var el = this; 
     $(el).click(function (e) { 
      e.preventDefault(); 
      handler.call(el, e); 
     }); 
    }); 
}; 
+0

我想我只是去了進深結......明白這段代碼是要帶我一個月。謹慎提供解釋,我的JavaScript/jQuery是生鏽的... – erroric 2014-07-04 18:09:08

+0

這是一個開始:http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean – erroric 2014-07-04 18:14:09