9

我正在尝试做的简化版本如下:

var indication = $('#some-div');
indication.bind('custom-event', function() { ... }


 // ... later on!

 function OtherThing() {
   $(this).trigger('custom-event');
 }

我想在不需要两人明确了解对方的情况下indication.bind('custom-event')收到触发器。function OtherThing这可能吗?到目前为止,我唯一的解决方案是将侦听器和事件绑定到 body ......这似乎很草率 - 有没有更好的方法?

4

1 回答 1

23

在 JavaScript 中,每个 HTML 元素上触发的事件都会传播到它们的父级,因此,为了解决您的问题并使任何元素能够处理自定义事件而不会做错事,例如$('*').bind('custom-event')将侦听器绑定到所有元素的公共父级, bodyorhtml元素:]

因此,您只需要将事件绑定到bodyhtml元素。然后,当所选父元素内的任何元素触发自定义事件时,它将传播到该父元素。

然后,在事件处理程序中,您可以通过访问target事件对象的属性来访问触发事件的元素:event.target

所以,代码应该是:

$('body').bind('custom-event', function(e){
  var $element = e.target;
});

$('#anyElement').trigger('custom-event');
于 2012-03-20T17:54:17.863 回答