作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的代码很乱,很抱歉。
JS 有效,但仅适用于第一次选择;我想让用户输入一个时间,但是如果用户那天不工作,我想禁用四个选择框。不幸的是,我不知道在 JS 中的何处添加其他选择。
还有另一个脚本可以填充选择的其余选项。我到目前为止的代码:
if (document.getElementById('holiday_check').checked)
document.getElementById('holiday_time_h1').setAttribute('disabled', 'disabled');
function closed_holiday() {
if (document.getElementById('holiday_check').checked)
document.getElementById('holiday_time_h1').setAttribute('disabled', 'disabled');
else
document.getElementById('holiday_time_h1').removeAttribute('disabled');
}
<div>
<span>Opening Time:</span>
<select id="holiday_time_h1"><option>00</option></select>
:
<select id="holiday_time_m1"><option>00</option></select>
<span>Closing time</span>
<select id="holiday_time_h2"><option>00</option></select>
:
<select id="holiday_time_m2"><option>00</option></select>
<input id="holiday_check" class="check" type="checkbox" onchange="closed_holiday();">Closed</input>
</div>
最佳答案
有多种方法可以中止这个问题。最常见和可忍受的方法是遍历每个选择并一一禁用它们。
首先,您需要为每个要禁用的选择元素获取一个数组。您可以将它们附加到同一类;让我们说“假期”,然后使用选择器 getElementsByClassName() 将它们全部放入一个数组中或 querySelector() .
完成后,您将遍历该元素数组,并在用户通过复选框元素选择禁用时禁用它们。
const mySelectElements = document.getElementsByClassName("holiday");
const holidayCheck = document.getElementById("holiday_check");
function closed_holiday(){
for(let selectElement of mySelectElements){
if(holidayCheck.checked){
selectElement.setAttribute('disabled', 'disabled');
}
else{
selectElement.removeAttribute('disabled');
}
}
}
<div>
<span>Opening Time:</span>
<select class="holiday" id="holiday_time_h1"><option>00</option></select>
:
<select class="holiday" id="holiday_time_m1"><option>00</option></select>
<span>Closing time</span>
<select class="holiday" id="holiday_time_h2"><option>00</option></select>
:
<select class="holiday" id="holiday_time_m2"><option>00</option></select>
<input id="holiday_check" class="check" type="checkbox" onchange="closed_holiday();">Closed</input>
</div>
关于javascript - 使用复选框禁用多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40991164/
我是一名优秀的程序员,十分优秀!