有没有一种巧妙的方法可以将事件处理程序绑定(bind)到元素而不考虑事件类型?
例如,我需要类似的东西:
$('#elem').bind(function(e){
//do stuff for any event originating from this element
e.stopPropagation();
});
最佳答案
您可以更改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 ) } );
噗:)
关于javascript - 为所有事件类型附加一个处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8655604/