views:

61

answers:

2

Hi all,

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.

+3  A: 

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);  
});
rahul
I can't see any alert boxes pop up by using your script:$("#container div").click(function(){ var imgID = this.id; alert(imgID); });
kwokwai
I am sorry,it works now
kwokwai
A: 

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>
Max Shawabkeh
I can't see any alert boxes pop up
kwokwai
I am sorry, it works now.
kwokwai