事件处理程序触发两次而不是一次

时间:2010-04-28 06:44:32

标签: javascript jquery

对不起,我在几分钟内问了两个问题。

在html文件中,我在父DIV标记中有三个子DIV标记:

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

现在当我点击三个子DIV标签时,我会看到弹出两个警告框而不是一个: 第一个警告框将显示如下内容: frag-123,第二个警告框将显示如下内容: 容器

我不知道为什么。 我只想获得子DIV的ID值,而不是父DIV的ID值。

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

}); 
</script>

请帮忙。

2 个答案:

答案 0 :(得分:6)

这是事件冒泡的情况。您可以通过提供

来停止事件冒泡
e.stopPropagation()

在click事件处理程序中。

尝试

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

如果你想将click事件绑定到容器div中的子elemets,那么你可以这样给出

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

答案 1 :(得分:1)

那是因为你将事件处理程序绑定到所有 DIV。相反,你想要的只是将它绑定到container中的DIV:

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

}); 
</script>
相关问题