事件处理程序触发两次,而不是一次 [英] Event handler triggered twice instead of once
问题描述
很抱歉,我在几分钟后问了两个问题.
I am sorry that I have asked two questions in a few minutes.
在一个html文件中,我在父DIV标签中得到了三个子DIV标签:
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>
现在,当我单击三个子DIV标签时,我将看到弹出两个警报框,而不是一个: 第一个警报框将显示以下内容: frag-123,第二个警告框将显示以下内容: 容器
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
我不知道为什么. 我只想获取子DIV的ID值,而不是父DIV的ID值.
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>
请帮助.
推荐答案
这是事件冒泡的情况.您可以通过以下方式停止事件冒泡
This is a case of event bubbling. You can stop event bubbling by giving
e.stopPropagation()
在点击事件处理程序内.
inside the click event handler.
尝试
$(function() {
$("div").click(function(e) {
var imgID = this.id;
alert(imgID);
e.stopPropagation() // will prevent event bubbling
});
});
如果您要将click事件绑定到容器div中的仅子元素,则可以这样设置
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);
});
这篇关于事件处理程序触发两次,而不是一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!