简体   繁体   中英

JQuery - Why event.target doesn't work in this situation?

just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

 $(window).on("click", function(event) { var container = $("#container"); if ((event.target) !== container) { alert("clicked outside"); } }); 
 body { height: 600px; } #container { padding: 2rem; background: grey; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> </div> 

Cheers

您应该使用.is()

if($(event.target).is(container))

Use the .is() function to compare the event target to your JQuery element :

 $(window).on("click", function(event) { var container = $("#container"); if ($(event.target).is(container)) { alert("clicked outside"); } }); 
 body { height: 600px; } #container { padding: 2rem; background: grey; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> </div> 

Compare the id . Here $("#container") is a jquery object

 $(window).on("click", function(event) { if ((event.target.id) !== 'container') { alert("clicked outside"); } }); 
 body { height: 600px; } #container { padding: 2rem; background: grey; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> </div> 

You're comparing a DOM element to a jQuery object which will never match. Create a jQuery object out of the target and check if it is a descendant of #container . This also works if you have child elements under #container .

Updated fiddle

$(window).on("click", function(event) {
  if ($(event.target).closest('#container').length == 0){
    alert("clicked outside");
  }
});

try this:

$(window).on("click", function(event) {
var container = $("#container");
if ((event.target) !== container[0]) {
    alert("clicked outside");
}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM