Wil*_*ill 9 jquery events custom-event
我正在尝试做的简化版本如下:
var indication = $('#some-div');
indication.bind('custom-event', function() { ... }
// ... later on!
function OtherThing() {
$(this).trigger('custom-event');
}
Run Code Online (Sandbox Code Playgroud)
我希望indication.bind('custom-event')得到触发器,function OtherThing而两人不必明确地了解彼此.这可能吗?到目前为止,我唯一的解决方案是将侦听器和事件绑定到正文......这看起来很草率 - 有更好的方法吗?
Raf*_*ger 22
在JavaScripts中,每个HTML元素上触发的事件都会传播到它们的父元素,因此,要解决您的问题并使任何元素能够处理自定义事件而不会出现错误,例如$('*').bind('custom-event')将侦听器绑定到所有元素的公共父级,body或html元素:]
因此,您只需要将事件绑定到body或html元素.然后,当在选择的父元素内的任何元素触发自定义事件时,它将传播到该父元素.
然后,在事件处理程序中,您可以通过访问target事件对象的属性来访问触发事件的元素:event.target
所以,代码应该是:
$('body').bind('custom-event', function(e){
var $element = e.target;
});
$('#anyElement').trigger('custom-event');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15310 次 |
| 最近记录: |