.item-extra {
color: red;
}
例如,我希望该组只有一个选项,但我也希望用户能够同时选择值4和5。
有没有办法做到这一点而无需复杂的逻辑?
这是我的剧本
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li class="item-extra">item extra</li>
</ul>
答案 0 :(得分:1)
var aCheckboxes = document.querySelectorAll("input[name='checkboxes[]']");
var aGroups = [
[1, 2, 3, 6],
[4, 5]
];
for (var i = 0; i < aCheckboxes.length; i++) {
aCheckboxes[i].addEventListener("change", function(e) {
checkGroups(e.target.value); //...call checkGroups...
});
}
function enableCheckboxes() {
for (var i = 0; i < aCheckboxes.length; i++) {
aCheckboxes[i].disabled = false;
}
}
function checkGroups(sCheckboxVal) {
var isOneChecked = false;
for (var x = 0; x < aCheckboxes.length; x++) { //Loop through all checkboxes
if (aCheckboxes[x].checked === true) { //is checkbox is checked
isOneChecked = true;
}
}
enableCheckboxes(); //Enable all checkboxes
if (isOneChecked === true) { //Is at least one checkbox is checked check groups
aGroups.forEach(function(aGroup) { //Loop throgh your groups
if (aGroup.indexOf(parseInt(sCheckboxVal)) === -1) { //Is checkbox not in group...
for (x = 0; x < aGroup.length; x++) { //...loop thorugh all checkboxes...
document.querySelectorAll("input[value='" + aGroup[x] + "']")[0].disabled = true; //...and disable checkbox
}
}
});
}
}
<input type="checkbox" name="checkboxes[]" value="1">
<input type="checkbox" name="checkboxes[]" value="2">
<input type="checkbox" name="checkboxes[]" value="3">
<input type="checkbox" name="checkboxes[]" value="4">
<input type="checkbox" name="checkboxes[]" value="5">
<input type="checkbox" name="checkboxes[]" value="6">