javascript jquery 多个事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12684857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery multiple event handlers
提问by aayush shrestha
I have defined event handlers according to their classnames in the latest project that I'm working on.
我在我正在处理的最新项目中根据它们的类名定义了事件处理程序。
for ex. all element with the class name "foo" should respond in a particular way on change event. and all elements with the class name "bar" should respond in some other way.
例如。具有类名“foo”的所有元素都应以特定方式响应更改事件。并且所有类名为“bar”的元素都应该以其他方式响应。
Now some of my elements fall under both classes i.e. class="foo bar" and they should respond in both ways. Right now, only one of the event handler function is being called.
现在我的一些元素属于这两个类,即 class="foo bar" 并且它们应该以两种方式响应。现在,只有一个事件处理函数被调用。
How can I make both the responses execute simultaneously.
如何使两个响应同时执行。
回答by 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 queuesthe event handlers instead of overwritingthe previous binding(s).
这取决于您如何绑定事件。如果您通过 jQuery 绑定它们而不是通过覆盖处理程序x.onchange = function() { ... }
- 所有绑定的事件处理程序都将被执行。这是因为 jQuery将事件处理程序排入队列,而不是覆盖之前的绑定。
Check this fiddle
to see multiple events getting fired:
and
检查这个fiddle
以查看多个事件被触发:
和
Check this fiddle
to see how the event handlers are overwritten causing only the last bound handler to fire
检查此fiddle
以查看事件处理程序如何被覆盖,从而仅触发最后一个绑定的处理程序
回答by 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.
通常的实现是监听“document”上的事件,然后通过event.target,定义动作。
For example: fiddle(http://jsfiddle.net/PRkAr/)
例如:小提琴(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.
这里的函数句柄处理带有您选择的类的元素上的所有事件。如果您希望添加其他事件或类,只需将它们附加到“on”列表中即可。