admin管理员组

文章数量:1327979

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.

本文标签: javascriptHow to check for a click in a parent elementbut not in the childStack Overflow