我有一个简单的checkbox,正在尝试确定它是否在 JS 中被检查。
var checkbox = document.getElementById('checkbox').checked;
console.log(checkbox);
if(checkbox == 'true'){
console.log('test');
}
Run Code Online (Sandbox Code Playgroud)
我的第一次console.log()返回true或false按预期返回,但是即使它从未进入if()语句,即使它是true.
我错过了什么?
要检查复选框是否被选中,您不要针对"true"(String)对其进行测试。相反,您检查其checked属性以查看它是否为true(Boolean)。这变得更容易处理,因为if条件总是首先测试“真实”值,因此您实际上不需要添加您正在测试的true.
var checkbox = document.getElementById('checkbox');
// Interpreted as "Is it true that checkbox.checked == true"?
if(checkbox.checked){
console.log('test');
}
var checkbox = document.getElementById('checkbox').checked;
// Interpreted as "Is checkbox.checked.checked true?", which is
// an error because the checkbox.checked property doesn't have
// a checked property and so checkbox.checked.checked will return
// undefined, which will be false when converted to a Boolean
if(checkbox.checked){
console.log('test');
}
Run Code Online (Sandbox Code Playgroud)
但是,无需检查是否选中了复选框。只需在文档中查询选中的复选框,返回的内容就是您使用的内容。
.querySelector()并.querySelectorAll()允许您将任何有效的 CSS 选择器传递给它们。.querySelector()将返回与选择器匹配的第一个元素,.querySelectorAll()并将返回所有匹配元素的节点列表(HTML 集合)。
var checkbox = document.getElementById('checkbox');
// Interpreted as "Is it true that checkbox.checked == true"?
if(checkbox.checked){
console.log('test');
}
var checkbox = document.getElementById('checkbox').checked;
// Interpreted as "Is checkbox.checked.checked true?", which is
// an error because the checkbox.checked property doesn't have
// a checked property and so checkbox.checked.checked will return
// undefined, which will be false when converted to a Boolean
if(checkbox.checked){
console.log('test');
}
Run Code Online (Sandbox Code Playgroud)
document.querySelector("button").addEventListener("click", function(){
// Query for only the checked checkboxes and put the result in an array
let checked = Array.prototype.slice.call(document.querySelectorAll("input[type='checkbox']:checked"));
console.clear();
// Loop over the array and inspect contents
checked.forEach(function(cb){
console.log(cb.value);
});
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12942 次 |
| 最近记录: |