2011-12-28 85 views
0

是否有一種簡潔的方式將事件處理程序綁定到某個元素,而與事件類型無關?爲所有事件類型附加處理程序

對於例如,我需要的是這樣的:

$('#elem').bind(function(e){ 

    //do stuff for any event originating from this element 
    e.stopPropagation(); 
}); 
+2

這個問題有一個類似的答案:http://stackoverflow.com/questions/5848598/how-all-events-of- dom-element-can-be-bind – 2011-12-28 12:01:29

+0

謝謝,不知何故,當我發佈這個時,它在'類似問題'部分沒有出現。 :)無論如何,我的問題說'整潔'我仍然想知道是否有其他方法來做到這一點。 – 2011-12-28 12:13:20

回答

3

您可以更改bind方法的默認行爲。 如果我們給出一個將會起作用的參數,將其添加到所有事件中 檢查了這一點。

$.fn.init.prototype.bind = (function(old) { 

    return function() { 
     if(arguments.length == 1 && typeof arguments[0] === "function") { 
      // if we'll put to bind method one argument which is function 

      // list of whole of events - you set themselves as needed 
      return this.bind("click keydown keyup keypress mouseover mouseenter mouseout mouseleave mousedown mouseup mousemove change blur focus scroll resize load unload beforeunload", arguments[0]); 

     } else { 
      // trigger original bind method 
      return old.apply(this, arguments) 
     } ; 
    } 

})($.fn.init.prototype.bind); 

現在:

$("body").bind(function() { console.log(this) }); 

噗:)

+0

酷:)要測試這個.. – 2011-12-28 12:30:53

+0

你看起來在插件開發人員的搖滾明星:) – 2011-12-28 12:40:35

0
var eventsList = "blur, focus, load, resize, 
       scroll, unload, beforeunload, click, dblclick, 
       mousedown, mouseup, mousemove, mouseover, mouseout, 
       mouseenter, mouseleave, change, select, submit, keydown, 
       keypress, keyup, error"; 

(/* selector of user choice */).bind(eventsList, function(){ 

//All operations here.. 
}); 

您可以在這裏找到事件的列表... JQuery Events

相關問題