Java click事件触发两次,即使使用stopPropagation [英] Javascript click event firing twice, even with stopPropagation

查看:243
本文介绍了Java click事件触发两次,即使使用stopPropagation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组类似的项目:

<label for="Cadenza-1" class="cars">
    <input type="checkbox" value="1" alt="Cadenza" id="Cadenza-1" name="vehicles[]">
    <img src="img/bill_murray_173x173.jpg">
    <span>Cadenza</span>
</label>

大约有13个。单击后,我想向标签添加一个类。但是,单击事件将触发两次。现在我正在调试click事件,然后添加该类:

there's about 13 of them. I want to add a class to the label when clicked. However, the click event fires twice. right now I'm debugging the click event then I'll add the class:

var cars = document.getElementsByClassName('cars');

for(var c = 0;c < cars.length; c++){
    cars[c].addEventListener("click", function(e){
        selectVehicle(cars[c],e);
    },false);
}

function selectVehicle(el,e) {
    console.log(e);
    e.stopPropagation();
}

console.log 触发两次。

推荐答案

尝试在stopPropogation之后添加preventDefault:

Try adding preventDefault after your stopPropogation:

function selectVehicle(el,e) {
    console.log(e);
    e.stopPropagation();
    e.preventDefault();
}

我认为最好将console.log(e)放在stopPropogation之后&虽然preventDefault。然后,您还需要实现将复选框设置为选中状态的功能,因为这样可以防止这种情况的发生。

I believe it is best to place console.log(e) after the stopPropogation & preventDefault though. You will also then need to implement functionality to set the checkbox to checked since this would prevent that from happening.

这篇关于Java click事件触发两次,即使使用stopPropagation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆