开发者

Event handler triggered twice instead of once

开发者 https://www.devze.com 2022-12-28 16:04 出处:网络
I am sorry that I have asked two questions in a few minutes. In a html file, I got three child DIV tags in a parent DIV tag:

I am sorry that I have asked two questions in a few minutes.

In a html file, I got three child DIV tags in a parent DIV tag:

<div id="container">
   <div id="frag-123">123</div>
   <div id="frag-124">124</div>
   <div id="frag-125">125</div>
</div>

Now when I click either the three child DIV tags, I will see two alert boxes pop up instead of one: The first alert box will开发者_运维问答 show something like this: frag-123, and the second alert box will show something like this: container

I dont know why. I just want to get the ID value of a child DIV, not the one from the parent DIV.

<script>
$(function() {
     $("div").click(function() {
          var imgID = this.id;
          alert(imgID);
     });

}); 
</script>

Please help.


This is a case of event bubbling. You can stop event bubbling by giving

e.stopPropagation()

inside the click event handler.

Try

$(function() {
     $("div").click(function(e) {
          var imgID = this.id;
          alert(imgID);
          e.stopPropagation() // will prevent event bubbling
     });
}); 

If you want to bind click event to only child elemets inside the container div then you can give like this

$("#container div").click(function(){
    var imgID = this.id;
    alert(imgID);  
});


That's because you're binding the event handler to all DIVs. Instead, what you want is bind it only to DIVs within container:

<script type="text/javascript">
$(function() {
     $("#container div").click(function() {
          var imgID = this.id;
          alert(imgID);
     });

}); 
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消