【问题标题】:Attach a handler for all event types为所有事件类型附加一个处理程序
【发布时间】:2011-12-28 11:55:56
【问题描述】:

是否有一种巧妙的方法可以将事件处理程序绑定到元素而不考虑事件类型?

例如,我需要类似的东西:

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

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

【问题讨论】:

  • 这个问题有类似的答案:stackoverflow.com/questions/5848598/…
  • 谢谢,不知何故,当我发布这篇文章时,它并没有出现在“类似问题”部分。 :) 无论如何,我的问题是“整洁”,我仍然想知道是否有其他方法可以做到这一点。

标签: javascript javascript-events jquery


【解决方案1】:

您可以更改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 ) } );

噗 :)

【讨论】:

  • 你在插件开发者中看起来像摇滚明星 :)
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2011-04-05
    • 2023-03-24
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多