简体   繁体   中英

Function is not called on click of div class?

I am using jQuery 1.7.2. Originally, my HTML was rendered on page load:

<div class="my_div_class">
  <button class="my_button_class" >
  </button>
<div>

Then I was registering below JavaScript function:

$(".my_div_class").on('click', function(event){ //function_1
}

It was working fine.

Because of some reason I need to change it to below

$(document).on('click','.my_div_class', function(event){}

Then its not working ? But If change above functiion to use my_button_class it works. Why it is not working with div ?

 $(document).ready(function() { $(document).on("click",".my_div_class",function(event) { alert("Heyy! clicked me!"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <div class="my_div_class"> <button class="my_button_class" > </button> <div> 

You can use $(event.target).closest(".my_div_class").length == 1 to see if you clicked on my_div_class or any element inside it.

$(document).on('click', function(event) {
  if ($(event.target).closest(".my_div_class").length == 1) {
    console.log("clicked on button or div")
  } else {
    console.log("clicked outside")
  }
})

demo

 $(document).on('click', function(event) { if ($(event.target).closest(".my_div_class").length == 1) { console.log("clicked on button or div") } else { console.log("clicked outside") } }) 
 .my_div_class { width:200px; background-color:yellow} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my_div_class"> <button class="my_button_class">click </button> <div> 

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