如何通过自定义事件传递浏览器事件?

How to pass browser event through the custom one?

http://jsfiddle.net/m2dqd236/

document.addEventListener('click', function (event) {
  $(document).trigger('click-anywhere', $.event.fix(event));
}, true);

$(document).on('click-anywhere', function (event, e) {
  console.log('>>> click-anywhere', arguments);
  console.log('target', event.target, e.target);
  console.log('originalEvent', event.originalEvent, e.originalEvent);
}).on('click', function (event) {
  console.log('>>> click', arguments);
  console.log('target', event.target);
  console.log('originalEvent', event.originalEvent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

<button>Click me</button>

当您点击上面示例中的按钮时,您会得到如下输出:

>>> click-anywhere [p.Event, p.Event]
target #document <button>​Click me​</button>​
originalEvent undefined MouseEvent {}
>>> click [p.Event]
target <button>​Click me​</button>​
originalEvent MouseEvent {}

如何让自定义事件的处理程序 click-anywhere 在第一个参数中获取正常事件?在当前实现中,我想在第一个参数中出现的事件在第二个参数中传递。

PS: Same question in Russian.

你不能用 jQuery 做到这一点,但你可以用原生事件做到这一点。

不要使用 jQuery trigger 来触发自定义事件,而是使用 dispatchEvent 并克隆现有的 MouseEvent(如果不这样做,浏览器将抛出异常事件已经发送)

document.addEventListener('click', function (event) {
  console.log(event);
  event.target.dispatchEvent(new MouseEvent('click-anywhere', event));
}, true);

$(document).on('click-anywhere', function (event) {
  console.log('>>> click-anywhere', arguments);
  console.log('target', event.target);
  console.log('originalEvent', event.originalEvent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

<button>Click me</button>