有没有办法检查气泡是否触发了点击? [英] Is there any way to check if bubble triggered the click?

查看:54
本文介绍了有没有办法检查气泡是否触发了点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击jQuery中的元素会导致冒泡到正文。如果我们有一个绑定到主体的点击处理程序显示警报,那么点击任何元素将冒泡到正文并触发警报。我的问题是,是否有任何方法可以知道身体警报是否是由于直接点击身体而触发的,或者是因为气泡到身体而触发了点击。

Clicking on elements in jQuery causes bubble up to body. If we have a click handler binded to body that shows an alert, then clicking on any element will bubble up to body and trigger the alert. My Question is, is there any way to know if the body alert was triggered as a result of direct click to body, or was the click triggered because of a bubble up to body.

推荐答案

比较 event.target 始终是绑定处理程序的事件; event.target 始终是发起事件的元素。

Compare event.target to this. this is always the event where the handler is bound; event.target is always the element where the event originated.

$(document.body).click(function(event) {
    if (event.target == this) {
        // event was triggered on the body
    }
});

如果您知道元素在文档中是唯一的(基本上只需 body )你也可以查看 nodeName 这个

In the case of elements you know to be unique in a document (basically, just body) you can also check the nodeName of this:

$(document.body).click(function(event) {
    if (event.target.nodeName.toLowerCase() === 'body') {
        // event was triggered on the body
    }
});

你必须做 toLowerCase()因为 nodeName 的情况在浏览器中不一致。

You have to do toLowerCase() because the case of nodeName is inconsistent across browsers.

最后一个选项是如果你的元素有一个ID就比较一,因为这些也必须是唯一的:

One last option is to compare to an ID if your element has one, because these also have to be unique:

$('#foo').click(function(event) {
    if (event.target.id === 'foo') {
        // event was triggered on #foo
    }
});

这篇关于有没有办法检查气泡是否触发了点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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