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

kwo*_*wai 1 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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

}); 
</script>
Run Code Online (Sandbox Code Playgroud)

请帮忙.

rah*_*hul 6

这是事件冒泡的情况.你可以通过给予来阻止事件冒泡

e.stopPropagation()
Run Code Online (Sandbox Code Playgroud)

在click事件处理程序中.

尝试

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

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

$("#container div").click(function(){
    var imgID = this.id;
    alert(imgID);  
});
Run Code Online (Sandbox Code Playgroud)