jQuery: more than one handler for same event

后端 未结 8 1238
终归单人心
终归单人心 2020-11-27 03:14

What happens if I bind two event handlers to the same event for the same element?

For example:

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


        
相关标签:
8条回答
  • 2020-11-27 03:44

    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.

    jQuery conforms to the DOM Level 2 event registration model:

    The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values

    0 讨论(0)
  • 2020-11-27 03:45

    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:

    $("...").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.

    0 讨论(0)
提交回复
热议问题