点击div触发绑定$('body'),点击 [英] clicking on div fires binding for $('body').click

查看:442
本文介绍了点击div触发绑定$('body'),点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,我想设置它,以便当我点击别的东西,它会隐藏div。



所以我做了

  $('body')点击(function(){
if(loginOpened)
{
$('#loginWindow')。animate({
'width':'0px',
' height':'0px'
},fast);
}
loginOpened = false;
});

但是,即使我点击div本身也会触发事件,是否有防止这种情况

解决方案

您可以使用



e.stopPropagation(); 如果有一个点击事件绑定到< div /> 标签。



请参阅 event.stopPropagation()


防止事件冒泡起来
的DOM树,防止任何父
处理程序被通知的
事件。


否则,您可以检查身体内部事件的目标点击。检查 event.target 是否与您的div相同。



请参阅 event.target


I have a div, I want to set it so that when I click on something else, it would hide the div.

So I did

$('body').click(function(){
    if(loginOpened)
    {
        $('#loginWindow').animate({
            'width':'0px',
            'height':'0px'
        },"fast");
    }
    loginOpened=false;
});

However, even when I click in the div itself the event is fired, is there anyway to prevent this?

解决方案

You can stop it using

e.stopPropagation(); if there is a click event bound to the <div /> tag.

See event.stopPropagation()

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Otherwise you can check the target of the event inside the body click. Check whether event.target is the same as your div.

See event.target

这篇关于点击div触发绑定$('body'),点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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