单击元素外部时的jQuery触发事件 [英] jQuery trigger event when click outside the element

查看:138
本文介绍了单击元素外部时的jQuery触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(document).click(function(evt) {
    var target = evt.currentTarget;
    var inside = $(".menuWraper");
    if (target != inside) {
        alert("bleep");
    }

});

我正在试图弄清楚如何让它如果用户点击某个div之外(menuWraper),它触发一个事件..我意识到我可以让每次点击触发一个事件,然后检查点击的currentTarget是否与从$(。menuWraper)中选择的对象相同。但是,这不起作用,currentTarget是HTML对象(?)而$(。menuWraper)是Object对象?我很困惑。

I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.

推荐答案

只需要你的 menuWraper 元素调用 event.stopPropagation()以便其点击事件不会冒泡到文档

Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.

尝试一下: http://jsfiddle.net/ Py7Mu /

$(document).click(function() {
    alert('clicked outside');
});

$(".menuWraper").click(function(event) {
    alert('clicked inside');
    event.stopPropagation();
});




  • http://api.jquery.com/event.stopPropagation/

    • http://api.jquery.com/event.stopPropagation/
    • 或者,您可以返回false; 而不是使用 event.stopPropagation();

      Alternatively, you could return false; instead of using event.stopPropagation();

      这篇关于单击元素外部时的jQuery触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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