最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check for a click in a parent element, but not in the child? - Stack Overflow

programmeradmin5浏览0评论

Code:

HTML

<!-- snip -->
<div class="parent" id="parent">
    <div class="child" id="child">
    </div>
</div>
<!-- snip -->

Javascript

/* snip */
$(function () {
    $("#parent").click(function () {
        alert("This dialog should only show up if the parent is clicked.");
    });
});
/* snip */

(This is just the basic structure of the actual code... some things are different in the actual code eg. the child is a jQuery UI Draggable element)

Code:

HTML

<!-- snip -->
<div class="parent" id="parent">
    <div class="child" id="child">
    </div>
</div>
<!-- snip -->

Javascript

/* snip */
$(function () {
    $("#parent").click(function () {
        alert("This dialog should only show up if the parent is clicked.");
    });
});
/* snip */

(This is just the basic structure of the actual code... some things are different in the actual code eg. the child is a jQuery UI Draggable element)

Share Improve this question asked Nov 13, 2010 at 4:03 aviraldgaviraldg 9,1747 gold badges42 silver badges59 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

The way JavaScript/DOM events work is that they "bubble" up from children to parents. So you just need to stop that at the child element:

$('#child').click(function(event) {
    event.stopPropagation();
});

See the jQuery documentation for .click() for more information. Alternatively, you could check to see what the originating element is within the parent's event handler using event.target.

Well, I'd do something like this:

$("#child").click(function() { });

Though that seems a bit ugly, it's guaranteed to work, I think.

发布评论

评论列表(0)

  1. 暂无评论