Javascript 切换复选框

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

Javascript toggle checkbox

javascripthtmlcheckbox

提问by I wrestled a bear once.

I need to toggle all buttons with a single function. Function needs to toggle all checkboxes in the document as my checkboxes are freestanding and not part of a form.

我需要用一个功能切换所有按钮。函数需要切换文档中的所有复选框,因为我的复选框是独立的,而不是表单的一部分。

I currently have this, but it is not working properly. I get syntax error: syntax errorin my firefox console.

我目前有这个,但它不能正常工作。我进入syntax error: syntax error了我的 Firefox 控制台。

    checked=false;
    function checkedAll() {
        var c = new Array();
        c = doc.getElementsByTagName('input');
        if (checked == false){
            checked = true;
        }else{
            checked = false;
        }
        for (var i = 0; i < c.length; i++){
            if (c[i].type == 'checkbox'){
                c[i].checked = checked;
            }
        }
    }

How can I fix my code?

我该如何修复我的代码?

Thanks

谢谢

回答by Kevin Bowersox

Two main items to refactor. First, instead of docit must be document. Second instead of relying on a global just pass in a boolean to determine whether or not to check the checkboxes.

要重构的两个主要项目。首先,doc它必须是document. 其次,不依赖于全局,只需传入一个布尔值来确定是否选中复选框。

function checkedAll(isChecked) {
    var c = document.querySelectorAll('input[type="checkbox"]');

    for (var i = 0; i < c.length; i++){
        c[i].checked = isChecked;
    }
}

JS Fiddle:http://jsfiddle.net/Jvnfm/107/

JS小提琴:http : //jsfiddle.net/Jvnfm/107/

回答by user9027325

You can alternatively perform the following for each checkbox element:

您也可以为每个复选框元素执行以下操作:

    c[i].click();

This version will trigger any associated event handlers associated with that element.

此版本将触发与该元素关联的任何关联事件处理程序。