jquery multiple event handlers

孤人 提交于 2019-12-01 15:53:43
techfoobar

It depends on how you are binding the events. If you are binding them via jQuery and not overwriting the handlers via x.onchange = function() { ... } - all the bound event handlers will get executed. This is because jQuery queues the event handlers instead of overwriting the previous binding(s).

Check this fiddle to see multiple events getting fired:
and

Check this fiddle to see how the event handlers are overwritten causing only the last bound handler to fire

Ilya Kantor

What you want is a variation of "behaviors" pattern.

It lets you to automatically process events on elements with given classes or other attributes.

The usual implementation is to listen to events on "document", and then, by event.target, define the action.

For example: fiddle(http://jsfiddle.net/PRkAr/)

$(document).on('click change', '.foo.bar', function(e) {
  var classes = this.className.split(/\s+/);
  $.each(classes, function(i, cls) {
    handle(e, this, cls);
  })
})

function handle(e, elem, cls) { 
  // example: Event type click on elem DIV with class foo
  alert("Event type " + e.type + " on elem " + elem.tagName + " with class " + cls);
} 

Here function handle with process all events on elements with classes of your choice. If you wish to add other events or classes, just append them into the "on" list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!