简体   繁体   English

使用事件侦听器更改单击时复选框的状态

[英]Using an event listener to change the state of a checkbox on click

I'd like to prevent the default behaviour when clicking on a checkbox (its new state will depend on an API response). 我想防止单击复选框时的默认行为(它的新状态取决于API响应)。

First I deactivate the default behaviour : 首先,我停用默认行为:

cb.addEventListener("click", function(e){
    e.preventDefault();
    e.stopPropagation();
}

Then I try to change myself the state of the checkbox : 然后我尝试更改自己的复选框状态:

cb.addEventListener("click", function(e){
    e.preventDefault();
    e.stopPropagation();
    console.log("Before : " + this.checked);
    this.checked = !this.checked;
    console.log("After : " + this.checked);
}

-> // If I start with a checked checkbox :
-> Before : false
-> After : true

-> // If I start with an unchecked checkbox :
-> Before : true
-> After : false

But with this I have two problems : 但这有两个问题:

  1. the state doesn't seem to change visually. 状态似乎在视觉上没有改变。
  2. The displayed value for my checkbox's checked attribute is the negative value of it's state right before toggling it and I don't understand why ( false when I start with a checked checkbox and true if it's not). 我的复选框的checked属性的显示值是在切换前状态的负值,我不明白为什么(当我从一个复选框开始时为false ,否则为true )。

Here is a fiddle . 这是一个小提琴

I also tried to bind the event listener to the change event. 我还尝试将事件侦听器绑定到change事件。

What I have tried is changed visual state on mousedown and skipped event prop on click 我尝试过的是在mousedown上更改视觉状态,并在click跳过事件属性

var cb = document.getElementById("checkbox");
cb.addEventListener("click", function(e) {       
    e.preventDefault();
});
cb.addEventListener("mousedown", function(e){
    e.preventDefault();
    e.stopPropagation();
    console.log("Before : " + this.checked, e.target.checked);
    e.target.checked = !this.checked;
    console.log("After : " + this.checked);
});

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

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