开发者

Using jquery to determine if any elements within a div was clicked

How can I tell using jQuery if an any element within a div (panel1) was clicked? I have this piece of code that I use to show/hide a popup:

$('body').click(function (e) {
        if ($(e.target).attr('id') == 'link1') {
            $('#panel1').show();
        } else {
            $('#panel1').hide();
        }
    });

The problem 开发者_开发技巧is that the popup (panel1) gets dismissed if I click on any control/element within panel1. I'd like to keep panel1 open unless an area outside panel1 is clicked (or if link1 is clicked again). How can I revise this code to achieve this? Thanks...


Try this

$('#panel1').click(function (e) {
       e.stopPropagation();
       //Other code if you want to execute anything on panel click.
    });

$('body').click(function (e) {
       if($("#panel1").is(":visible")) 
          $('#panel1').hide();
    });


Make a following html markup:

<body>
<div id="div1">
... all the body content here
</div>
<div id="panel1">
</div>

I suppose the popup #panel1 is positioned out of normal flow anyway, so it is no problem. Then in jquery use div1 instead of body and that's it :-)


$('body').click(function (e) {
        if ($(e.target).attr('id') == 'link1') {
            $('#panel1').show();
        } else if($(e.target).attr('id') != 'panel1') {
           $('#panel1').hide();
        }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜