我有这个多选复选框的方案,我需要p.label
来触发.item
复选框(它的子复选框);
但我的JS脚本只有在单击.labels
个时才能工作,它选中/取消选中复选框,但输入when I click directly on the checkboxes个,我需要复选框具有复选框的正常行为,并忽略添加到所有标签的onclick
事件.
In short:我需要列表中的项目可以通过标签或直接在框中 Select .我如何修复我的脚本以防止正在发生的碰撞?
let fruits_labels = document.querySelectorAll("#fruits .label");
let fruits_items = document.querySelectorAll("#fruits .label .item");
fruits_labels.forEach((label, index) => {
label.onclick = (event) => {
console.log("index: " + index);
fruits_items[index].checked = (fruits_items[index].checked == true) ? false : true;
}
});
let colors_labels = document.querySelectorAll("#colors .label");
let colors_items = document.querySelectorAll("#colors .label .item");
colors_labels.forEach((label, index) => {
label.onclick = (event) => {
console.log("index: " + index);
colors_items[index].checked = (colors_items[index].checked == true) ? false : true;
}
});
div.container{ margin: 0; padding: 0; margin-bottom: 10px; width: 200px; border: 1px solid black; }
div.container p.label { margin: 0; padding: 4px 8px; display: flex; align-items: center; border: 1px solid magenta; }
div.container p.label:hover { background-color: yellow; }
div.container p.label input[type=checkbox].item{ margin-right: 6px; }
<div class="container" id="fruits">
<p class="label"><input class="item" type="checkbox">APPLE</p>
<p class="label"><input class="item" type="checkbox">BANANA</p>
<p class="label"><input class="item" type="checkbox">KIWI</p>
<p class="label"><input class="item" type="checkbox">LEMON</p>
<p class="label"><input class="item" type="checkbox">ORANGE</p>
</div>
<div class="container" id="colors">
<p class="label"><input class="item" type="checkbox">RED</p>
<p class="label"><input class="item" type="checkbox">GREEN</p>
<p class="label"><input class="item" type="checkbox">BLUE</p>
</div>