如何检查是否使用JavaScript选中了复选框?

Inspect the checked property of the element.

检查元素的checked属性。

Say you have this checkbox:

说您有这个复选框:

<input type="checkbox" class="checkbox" />

You can see if it’s checked using

您可以查看是否已使用进行了检查

document.querySelector('.checkbox').checked

You can also check if looking for .checkbox:checked does not return null:

您还可以检查寻找.checkbox:checked是否不返回null

document.querySelector('.checkbox:checked') !== null

but I think looking for .checked is cleaner.

但我认为寻找.checked更干净。

Do NOT use getAttribute() looking for the checked attribute value, because that’s always true if the checkbox is checked by default in this way:

不要使用getAttribute()查找已checked属性值,因为如果默认情况下以这种方式选中了此复选框,则始终为true:

<input type="checkbox" checked />

Also don’t check for the value of a checkbox element. It’s always on, regardless whether the checkbox is checked or not.

也不要检查复选框元素的value 。 它始终on ,无论是否选中该复选框。

翻译自: https://flaviocopes.com/how-to-check-checkbox-checked/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值