附加所有事件类型的处理程序 [英] Attach a handler for all event types

查看:74
本文介绍了附加所有事件类型的处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简洁的方法将事件处理程序绑定到一个元素而不管事件类型如何?

Is there a neat way to bind an event handler to an element irrespective of event type?

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

For eg, I need something like:

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

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


推荐答案

您可以更改<$ c $的默认行为c> bind 方法。
如果我们给出一个将起作用的参数,将其添加到所有事件中
检查出来。

You can change the default behavior of bind method. If we give a one argument which will function add this to all events Check this out.

$.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 ) } );

Poof:)

这篇关于附加所有事件类型的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆