jquery .on本身 [英] jquery .on itself

查看:86
本文介绍了jquery .on本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个元素来监听一个自己实际触发的自定义事件。自定义事件可以从后代触发,但应该被忽略。它的重要性源于自身。它也需要是一个事件,因为我可能需要额外的祖先来听事件。

I want an element to listen for a custom event that is actually triggered by itself. The custom event could possibly be triggered from a descendant but should then be ignored. It's important that it origins from itself. It also needs to be an event since I might need additional ancestors to listen for the events.

.on( http://api.jquery.com/on/ )方法能够提供此功能。选择器参数可以用作过滤器。但是,这样做可以过滤掉侦听器元素本身。

The .on (http://api.jquery.com/on/) method is able to provide this functionality. The selector argument can be used as filter. However this does not work to filter out the listener element itself.

简而言之:

- 事件必须能够泡泡

- 触发器和侦听器是相同的元素

- 如果由祖先触发,则监听器必须忽略该自定义事件

In short:
-The event must be able to bubble
-The trigger and the listener is the same element
-The listener must ignore the custom event if it's triggered by an ancestors

如何实现?

请求使用案例

我使用jquery UI对话框小部件

I use the jquery UI dialog widget

$el = $('#dialogDiv');
$el.on('customEvent', $el /* Won't work */, function() {
    //Do whatever
});
$el.dialog({
    open: function() {
        $el.trigger('customEvent');
    }
});


推荐答案

.on 工作正常忽略祖先检查 e.target

.on works fine; to ignore ancestors check e.target:

$el.on('customEvent', function(e) {
  if(e.target === this) {
    //Do whatever
  }
});

这篇关于jquery .on本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆