[英]JavaScript check if checkbox checked
我想使用復選框更改背景顏色,但只能使用一次。 意味着如果我再次單擊它,則沒有任何變化。
<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>
Element.getElementsByTagName()
方法返回具有給定標簽名稱的元素的實時HTMLCollection。
在這種情況下,您根本不需要使用getElementsByTagName()
。 只是通過this
來的功能,使您可以參考函數體中像下面這個元素:
function check(chk) { if (chk.checked) { document.body.style.backgroundColor = 'white'; } else { document.body.style.backgroundColor = 'black'; } }
<body> <label class="switch"> <input type="checkbox" onclick="check(this);"> <span class="slider round"></span> </label> </body>
由於getElementsByTagName
將響應元素列表。 在您的情況下,您必須選擇第一個元素以checked
function check() { if (document.getElementsByTagName('input')[0].checked) { document.body.style.backgroundColor = 'white'; } else { document.body.style.backgroundColor = 'black'; } } check();
<body> <label class="switch"> <input type="checkbox" onclick="check();"> <span class="slider round"></span> </label> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.