最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - jquery, on click anywhere inside div except certain child - Stack Overflow

matteradmin6PV0评论

I've got the following html

<div id="parent">
   <div id="window"><!-- contents of window ---></div>
</div>

Parent is 100% width with padding top and bottom and Window is centered inside it with a width of 600px.

What I need to figure out is a jquery selector which will trigger when the user clicks anywhere that is inside of Parent but outside of Window

I've got the following html

<div id="parent">
   <div id="window"><!-- contents of window ---></div>
</div>

Parent is 100% width with padding top and bottom and Window is centered inside it with a width of 600px.

What I need to figure out is a jquery selector which will trigger when the user clicks anywhere that is inside of Parent but outside of Window

Share Improve this question asked Sep 13, 2013 at 15:18 user1354269user1354269 354 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Check if the target has id parent

$('#parent').on('click', function (e) {
    if (e.target.id == "parent") {
        //code for clicking outside window but inside parent
    }
});

DEMO

You can bind a click handler to #parent and then prevent propagation of clicks from #window. This allows you to have additional nested content inside of #parent without messing around with lists of the event targets.

$("#window").on("click", function(e) {
    e.stopPropagation();
});
$("#parent").on("click", function(e) {
    // Do your thing
});

See a demo here: http://jsfiddle/4kGJX/

you can try this way

$('#parent').not("#window").on('click', function (e) {
    //do stuff
});

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far