最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - multiple event listeners for same button - Stack Overflow

programmeradmin2浏览0评论

Say I have an button with an id:

<input id='someButton' />

I want to attach an event listener on this button:

$('#form').on('click', '#someButton', function() { 
   alert("My listener called"); 

});

However, unbeknownst to me, someone previously wrote an event listener for this very same button:

$('#form').on('click', '#someButton', function() { 
   alert("Some other listener called"); 
});

I encountered some code that effectively does the same thing as above, and it seems like the first listener registered is the one that is used. Am I correct in assuming jQuery will always call the first event listener registered on a specific id (and only that listener)?

Say I have an button with an id:

<input id='someButton' />

I want to attach an event listener on this button:

$('#form').on('click', '#someButton', function() { 
   alert("My listener called"); 

});

However, unbeknownst to me, someone previously wrote an event listener for this very same button:

$('#form').on('click', '#someButton', function() { 
   alert("Some other listener called"); 
});

I encountered some code that effectively does the same thing as above, and it seems like the first listener registered is the one that is used. Am I correct in assuming jQuery will always call the first event listener registered on a specific id (and only that listener)?

Share Improve this question asked Mar 12, 2013 at 18:39 Ben SiverBen Siver 2,9481 gold badge27 silver badges43 bronze badges 1
  • 1 nope. in jquery you can add multiple event listeners.. – honk31 Commented Mar 12, 2013 at 18:41
Add a ment  | 

2 Answers 2

Reset to default 7

Incorrect. jQuery will call ALL event listeners bound to an element, in the order they were bound.

To remove an existing event handler, use .off():

$('#form').off('click'); // click event handler(s) removed
$('#form').off(); // all event handler(s) removed

Be aware that events delegated from ancestor DOM elements won't be removed this way, though.

you could use mousedown:

$('#form').on('mousedown', '#someButton', function() { 
    alert("My listener called"); 
});

Hope this help.

发布评论

评论列表(0)

  1. 暂无评论