简体   繁体   English

Onclick被调用两次

[英]Onclick is called twice

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 ,但是当跨度时 - spanbutton都被警告 - 因此onclick函数被调用两次。

How can I prevent this? 我怎么能阻止这个? I need onclick to be called only once. 我需要onclick才能被调用一次。

event.preventDefault(); instead of event.stopPropagation(); 而不是event.stopPropagation(); triggers onclick on the clicked element only. 触发onclick只有点击的元素上。 A demo at jsFiddle . jsFiddle演示。

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>

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. 只需在标签中提供“for”值,并使用不存在的ID。

Hope it helps.. 希望能帮助到你..

...click event gets fired twice when user click on any of the item in iscroll... ...当用户点击iscroll中的任何项目时,click事件会被触发两次...

https://groups.google.com/forum/#!topic/iscroll/XL2Ny9gpKc0 https://groups.google.com/forum/#!topic/iscroll/XL2Ny9gpKc0

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){ function selectIconElement(elem,event){

if(event.target.id.indexOf('label')>0){
    //do something if its label
}else{
    //do something if not label
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM