是否有一种简洁的方法可以将事件处理程序绑定到元素而不考虑事件类型?例如,我需要以下内容:
$('#elem').bind(function(e){ //do stuff for any event originating from this element e.stopPropagation(); });
oxcyiej71#
你可以改变bind方法的默认行为。如果我们给予一个参数,它将起作用,把它添加到所有事件中。
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 ) } );
噗的一声:)
oxiaedzo2#
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
2条答案
按热度按时间oxcyiej71#
你可以改变
bind
方法的默认行为。如果我们给予一个参数,它将起作用,把它添加到所有事件中。现在:
噗的一声:)
oxiaedzo2#
您可以在此处找到事件列表... JQuery Events