在 DOM Javascript 中使用多个 ID
Use multiple ID'S in DOM Javascript
主要思想是尝试使用多个 ID'S 禁用多个复选框,例如 使用 documentGetElementById
每个 id 都属于一个复选框
function main(){
var a = document.getElementById("actual").value;
var b = document.getElementById("destination").value;
if (a == "Jamaica" && b == "Paris"){
document.getElementById("A", "B", "C", "D").disabled = true; // occupied seats
}
}
getElementById
只有一个参数,因此,你应该这样做:
let ids = ["A", "B", "C", "D"];
for(let i = 0; i < ids.length; i++)
document.getElementById(ids[i]).disabled = true; // occupied seat
您有三个选择:
1.) 多次调用
document.getElementById("A").disabled = true;
document.getElementById("B").disabled = true;
// and so on...
2.) 遍历 ID
["A", "B", "C", "D"].forEach(id => document.getElementById(id).disabled = true)
3.) 你找到一个 selector 匹配所有这些并使用 document.querySelectorAll
。 ID 必须是唯一的,所以这还不够,但假设需要禁用页面上的所有复选框:
document.querySelectorAll("input[type='checkbox']").forEach(elem => elem.disabled = true);
对于此选项,您可以选择使用其他 CSS select 或 select 所需的复选框,例如 class 名称。
主要思想是尝试使用多个 ID'S 禁用多个复选框,例如 使用 documentGetElementById
每个 id 都属于一个复选框
function main(){
var a = document.getElementById("actual").value;
var b = document.getElementById("destination").value;
if (a == "Jamaica" && b == "Paris"){
document.getElementById("A", "B", "C", "D").disabled = true; // occupied seats
}
}
getElementById
只有一个参数,因此,你应该这样做:
let ids = ["A", "B", "C", "D"];
for(let i = 0; i < ids.length; i++)
document.getElementById(ids[i]).disabled = true; // occupied seat
您有三个选择:
1.) 多次调用
document.getElementById("A").disabled = true;
document.getElementById("B").disabled = true;
// and so on...
2.) 遍历 ID
["A", "B", "C", "D"].forEach(id => document.getElementById(id).disabled = true)
3.) 你找到一个 selector 匹配所有这些并使用 document.querySelectorAll
。 ID 必须是唯一的,所以这还不够,但假设需要禁用页面上的所有复选框:
document.querySelectorAll("input[type='checkbox']").forEach(elem => elem.disabled = true);
对于此选项,您可以选择使用其他 CSS select 或 select 所需的复选框,例如 class 名称。