javascript Onclick 被调用两次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15220591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Onclick is called twice
提问by k102
Here's the code:
这是代码:
<label onclick="event.stopPropagation(); alert(event.target.innerHTML);">
<button>
button
</button>
<span>
span
</span>
</label>
(and the fiddle: http://jsfiddle.net/YsYKq/1/)
(和小提琴:http: //jsfiddle.net/YsYKq/1/)
If one clicks on the button, only button
is alerted, but when on span - both span
and button
are alerted - so the onclick
function is called twice.
如果单击该按钮,则只会button
发出警报,但是在跨度上时 -span
和 都会button
发出警报 - 因此该onclick
函数会被调用两次。
How can I prevent this? I need onclick
to be called only once.
我怎样才能防止这种情况?我只需要onclick
被调用一次。
回答by Teemu
回答by Kevin G Flynn
Please try below code i am editing your code and change "stopPropagation" to "preventDefault".
请尝试下面的代码,我正在编辑您的代码并将“stopPropagation”更改为“preventDefault”。
<label onclick="event.preventDefault(); alert(event.target.innerHTML);">
<button>
button
</button>
<span>
span
</span>
</label>
回答by Sukrit Gupta
Suggestion by @BenM Goes Perfect But if you still want to use enclosing button and span then here's a way...
@BenM 的建议非常完美但是如果您仍然想使用封闭按钮和跨度,那么这里有一种方法......
<label for="notExistingId" onclick="event.stopPropagation(); alert(event.target.innerHTML);">
<button>
button
</button>
<span>
span
</span>
Just provide a value of 'for' in label with an ID which do not exist.
只需在标签中提供一个不存在的 ID 的 'for' 值。
Hope it helps..
希望能帮助到你..
回答by diyism
...click event gets fired twice when user click on any of the item in iscroll...
...当用户单击 iscroll 中的任何项目时,click 事件会被触发两次...
回答by Anand Tuli
I have solved this using different id field for label and checkbox - and then testing event.target.label for label script
我已经使用标签和复选框的不同 id 字段解决了这个问题 - 然后为标签脚本测试 event.target.label
function selectIconElement(elem, event){
功能选择图标元素(元素,事件){
if(event.target.id.indexOf('label')>0){
//do something if its label
}else{
//do something if not label
}
}
}