JavaScript检查是否选中复选框

JavaScript检查是否选中复选框,javascript,html,Javascript,Html,我想使用复选框更改背景色,但它只能工作一次。我的意思是,如果我再次点击它,一切都不会改变 <body> <label class="switch"> <input type="checkbox" onclick="check();"> <span class="slider round"></span> </label> </body> <script>

我想使用复选框更改背景色,但它只能工作一次。我的意思是,如果我再次点击它,一切都不会改变

<body>
    <label class="switch">
        <input type="checkbox" onclick="check();">
        <span class="slider round"></span>
    </label>
</body>

<script>
    function check() {
        if (document.getElementsByTagName('input').checked) {
            document.body.style.backgroundColor = 'white';
        } else {
            document.body.style.backgroundColor = 'black';
        }
    }
</script>

函数检查(){
if(document.getElementsByTagName('input')。选中){
document.body.style.backgroundColor='白色';
}否则{
document.body.style.backgroundColor='黑色';
}
}
该方法返回具有给定标记名的元素的活动HTMLCollection

在这种情况下,根本不需要使用
getElementsByTagName()
。只需将
传递给函数,您就可以在函数体中引用该元素,如下所示:
功能检查(chk){
如果(已检查){
document.body.style.backgroundColor='白色';
}否则{
document.body.style.backgroundColor='黑色';
}
}

因为
getElementsByTagName
将响应元素列表。在您的情况下,必须选择第一个元素来检查选中的
checked

函数检查(){
if(document.getElementsByTagName('input')[0]。选中){
document.body.style.backgroundColor='白色';
}否则{
document.body.style.backgroundColor='黑色';
}
}
检查()

getElementsByTagName('input')的可能重复项
返回一个列表,请执行
getElementsByTagName('input')[0]
尝试使用此答案搜索您的问题