简体   繁体   English

jQuery:同一事件的多个处理程序

[英]jQuery: more than one handler for same event

What happens if I bind two event handlers to the same event for the same element? 如果我将两个事件处理程序绑定到同一个元素的同一事件会发生什么?

For example: 例如:

var elem = $("...")
elem.click(...);
elem.click(...);

Does the last handler "win", or will both handlers be run? 最后一个处理程序是“win”,还是两个处理程序都会运行?

Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler. 两个处理程序都将运行,jQuery事件模型允许一个元素上有多个处理程序,因此后来的处理程序不会覆盖旧的处理程序。

The handlers will execute in the order in which they were bound . 处理程序将按照绑定的顺序执行

Suppose that you have two handlers, f and g , and want to make sure that they are executed in a known and fixed order, then just encapsulate them: 假设你有两个处理程序fg ,并且想要确保它们以已知和固定的顺序执行,那么只需封装它们:

$("...").click(function(event){
  f(event);
  g(event);
});

In this way there is (from the perspective of jQuery) only one handler, which calls f and g in the specified order. 通过这种方式(从jQuery的角度来看)只有一个处理程序,它以指定的顺序调用fg

jQuery's .bind() fires in the order it was bound : jQuery的.bind()以绑定的顺序触发

When an event reaches an element, all handlers bound to that event type for the element are fired. 当事件到达元素时,将触发绑定到该元素的该事件类型的所有处理程序。 If there are multiple handlers registered, they will always execute in the order in which they were bound. 如果注册了多个处理程序,它们将始终按照绑定的顺序执行。 After all handlers have executed, the event continues along the normal event propagation path. 在执行所有处理程序之后,事件沿着正常事件传播路径继续。

Source: http://api.jquery.com/bind/ 资料来源: http//api.jquery.com/bind/

Because jQuery's other functions (ex. .click() ) are shortcuts for .bind('click', handler) , I would guess that they are also triggered in the order they are bound. 因为jQuery的其他函数(例如.click() )是.bind('click', handler)快捷方式,我猜它们也会按照绑定的顺序触发。

You should be able to use chaining to execute the events in sequence, eg: 您应该能够使用链接按顺序执行事件,例如:

$('#target')
  .bind('click',function(event) {
    alert('Hello!');
  })
  .bind('click',function(event) {
    alert('Hello again!');
  })
  .bind('click',function(event) {
    alert('Hello yet again!');
  });

I guess the below code is doing the same 我想下面的代码也是这样做的

$('#target')
      .click(function(event) {
        alert('Hello!');
      })
      .click(function(event) {
        alert('Hello again!');
      })
      .click(function(event) {
        alert('Hello yet again!');
      });

Source: http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3 资料来源: http//www.peachpit.com/articles/article.aspx?p = 1371947& seqNum = 3

TFM also says: TFM还说:

When an event reaches an element, all handlers bound to that event type for the element are fired. 当事件到达元素时,将触发绑定到该元素的该事件类型的所有处理程序。 If there are multiple handlers registered, they will always execute in the order in which they were bound. 如果注册了多个处理程序,它们将始终按照绑定的顺序执行。 After all handlers have executed, the event continues along the normal event propagation path. 在执行所有处理程序之后,事件沿着正常事件传播路径继续。

Both handlers get called. 两个处理程序都被调用。

You may be thinking of inline event binding (eg "onclick=..." ), where a big drawback is only one handler may be set for an event. 您可能正在考虑内联事件绑定 (例如"onclick=..." ),其中一个很大的缺点是只能为事件设置一个处理程序。

jQuery conforms to the DOM Level 2 event registration model : jQuery符合DOM Level 2事件注册模型

The DOM Event Model allows registration of multiple event listeners on a single EventTarget. DOM事件模型允许在单个EventTarget上注册多个事件侦听器。 To achieve this, event listeners are no longer stored as attribute values 为此,事件侦听器不再存储为属性值

Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. 使用2种方法使其成功运行:Stephan202的封装和多个事件监听器。 I have 3 search tabs, let's define their input text id's in an Array: 我有3个搜索选项卡,让我们在数组中定义他们的输入文本ID:

var ids = new Array("searchtab1", "searchtab2", "searchtab3");

When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. 当searchtab1的内容发生变化时,我想更新searchtab2和searchtab3。 Did it this way for encapsulation: 这样做是为了封装:

for (var i in ids) {
    $("#" + ids[i]).change(function() {
        for (var j in ids) {
            if (this != ids[j]) {
                $("#" + ids[j]).val($(this).val());
            }
        }
    });
}

Multiple event listeners: 多个事件监听器:

for (var i in ids) {
    for (var j in ids) {
        if (ids[i] != ids[j]) {
            $("#" + ids[i]).change(function() {
                $("#" + ids[j]).val($(this).val());
            });
        }
    }
}

I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. 我喜欢这两种方法,但程序员选择了封装,但是多个事件监听器也可以工作。 We used Chrome to test it. 我们用Chrome测试它。

There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. 有一种解决方法可以保证一个处理程序在另一个处理程序之后发生:将第二个处理程序附加到包含元素并让事件冒出来。 In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in. 在附加到容器的处理程序中,您可以查看event.target并执行某些操作,如果它是您感兴趣的那个。

Crude, maybe, but it definitely should work. 可能是原油,但绝对应该有效。

jquery will execute both handler since it allows multiple event handlers. jquery将执行两个处理程序,因为它允许多个事件处理程序。 I have created sample code. 我已经创建了示例代码。 You can try it 你可以尝试一下

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM