jQuery: more than one handler for same event

后端 未结 8 1396
终归单人心
终归单人心 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:23

    You should be able to use chaining to execute the events in sequence, e.g.:

    $('#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

    TFM also says:

    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.

提交回复
热议问题