使用 JavaScript 切换复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37286629/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:09:27  来源:igfitidea点击:

Toggle Checkbox using JavaScript

javascripthtmlif-statement

提问by Kervvv

I had this working, but I didnt save and cannot replicate. I am trying to toggle checkboxes using if else. What am I doing wrong.

我有这个工作,但我没有保存并且无法复制。我正在尝试使用if else. 我究竟做错了什么。

What I thought would work:

我认为会起作用的:

function myForm() {
    var inputs = document.getElementsByTagName("input");
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i].type == "checkbox") { 
            if(inputs[i].checked = false) {
                inputs[i].checked = true; 
            } else {
                if(inputs[i].checked = true) {
                    inputs[i].checked = false; 
                }   
            }
        }  
    } 
}

采纳答案by IrkenInvader

Single equals is assignment, double/triple equals is for equality. You need to use double or triple equals in your if/else block.

单等号是赋值,双/三等号是等号。您需要在 if/else 块中使用双等号或三等号。

    if(inputs[i].checked == false) {
        inputs[i].checked = true; 
    }
    else {
        if(inputs[i].checked == true) {
            inputs[i].checked = false; 
         }   
    }

回答by Ali Seyfollahi

It can be easier:

它可以更容易:

inputs[i].checked = !inputs[i].checked;

回答by Alex Stragies

How about using an operator, that is defined to toggle booleans using 1 as second operand?

如何使用运算符,该运算符定义为使用 1 作为第二个操作数来切换布尔值?

inputs[i].checked ^= 1;

This uses the XORCompound assigment operator, and it toggles booleans because ?A ≡ A ^ 1.

这使用XOR复合赋值运算符,并且它切换布尔值,因为?A ≡ A ^ 1.

It also doesn't require looking up inputs[i]a second time.

它也不需要inputs[i]第二次查找。

回答by SnowballsChance

I thought I would add to this since it led me to an answer I was seeking for checking all checkboxes with bookmarklet. Using the bitwise operator worked like a charm in IE 11 and Chrome. Haven't tried it in other browsers.

我想我会添加这个,因为它让我找到了一个答案,我正在寻找使用书签检查所有复选框的答案。在 IE 11 和 Chrome 中使用按位运算符就像一个魅力。其他浏览器没试过。

javascript:(function(){var chbxs=document.querySelectorAll('input');for(i in chbxs){chbxs[i].checked^=1;}})();

回答by Matthew Montes de Oca

Another correct answer could be:

另一个正确答案可能是:

inputs[i].checked = input.checked ? false : true;