“$(document).on” not triggering after event.stopPropagation and “$(a).on” not triggering for new elements

大兔子大兔子 提交于 2019-12-11 12:48:20

问题


I'm trying to write a chrome extension (for casperjs testing). A part of the extension needs to bind to the click event which I'm doing like this:

$(document).on('click', 'a', null, handler)

This works great for all links, including any newly created elements. Problem is if a link has it's own click handler that calls the event.stopPropagation() method then the .on does not trigger the handler.

The workaround is I bind to the a elements like this:

$('a').on('click', null, null, handler)

This works fine and triggers the handler even if another event handler calls the event.stopPropagation() method. Problem is it does not work for dynamically created elements. So, any new elements created do not trigger the handler.

So I need something that has the functionality of the $(document).on method that triggers for dynamically created elements, but which also triggers regardless the event.stopPropagation() method.

Any ideas?


回答1:


Any ideas?

Event handling is separated in two phases: capturing phase and bubbling phase:

                 | |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------

By default event handlers are bound to listen to the bubbling phase (event handlers bound with jQuery as well).

To react to the event before the element's own event handler is called, you have to bind the handler to the capturing phase. Note that especially older IE browsers don't support this.

Since jQuery doesn't let you do this, you have to use the DOM API directly:

document.addEventListener('click', function(event) {
  // test whether event originates inside <a> first 
  // (search on SO to find out how)
  // then:
  handler.call(event.target, event);
}, true);

document.addEventListener('click', function(event) {
  if (event.target.nodeName !== 'BUTTON') {
    return;
  }
  console.log('Called first.');
}, true);
document.addEventListener('click', function(event) {
  if (event.target.nodeName !== 'BUTTON') {
    return;
  }
  console.log('Called last.');
});
document.querySelector('button').onclick = function(event) {
  console.log('Called in between (could cancel bubbling here)');
  // event.stopPropagation();
};
<button>Click me and look at the console</button>


来源:https://stackoverflow.com/questions/33598841/document-on-not-triggering-after-event-stoppropagation-and-a-on-not-tr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!