简体   繁体   中英

jQuery that executes only when a child element in the parent div is clicked

I have a div element with some child controls in it (dropdowns and check boxes).

I need some jquery that will run when any of the child elements are clicked, but not when the empty space in the div is clicked.

What is the proper jQuery to accomplish this?

Roughly something like this

$('YourDivSelector *').click(function(){
   // your stuff here
});

Only attaching the click to the child elements as shown by the answer of mguimard is the best approach. In case the contents of the div are dynamic however, you could use event.target to check if the element being clicked is the same as the element that the function is attached to as follows:

$('#YourDivID').click(function(e){  
  if(e.target!==this)
     console.log('child element clicked');  
});

You can check if a children is clicked with target.nodeName ex :

$("#div").click(function(event) {
    console.log("clicked: " + event.target.nodeName);
});

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