dispatchEvent不会触发jQuery.on()事件侦听器

Bog*_*dan 4 javascript jquery

我有以下代码触发自定义命名事件:

elem.addEventListener('click', function (event)
{
    event.preventDefault();

    // Do some processing stuff

    var event = new Event('custom_event');
    this.dispatchEvent(event);
});
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用jQuery.on()捕获自定义事件,它可以工作,但只有当我不使用后代选择器过滤器时.

这样可行:

$('selector').on('custom_event', function () { // works });
Run Code Online (Sandbox Code Playgroud)

但这不是:

$(document).on('custom_event', 'selector', function () { // doesn't work });
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么会这样吗?这是一个显示问题的小提琴.

Aru*_*hny 13

默认情况下,事件不会冒泡,因此在创建事件时,您需要bubbles: true作为选项传递,以指示您希望事件被冒泡.您可以使用CustomEvent来执行此操作.

您正在使用事件委派来注册第二个处理程序,该处理程序使用事件冒泡来工作.

document.querySelectorAll('.button')[0].addEventListener('click', function(e) {
  var event = new CustomEvent('custom_event', {
    bubbles: true
  });
  this.dispatchEvent(event);
});

$(document).on('custom_event', '.button', function() {
  alert('Custom event captured [selector filter]');
});

$('.button').on('custom_event', function() {
  alert('Custom event captured');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="button">Click Me</button>
Run Code Online (Sandbox Code Playgroud)