1 回答

TA貢獻1155條經驗 獲得超0個贊
您可以使用querySelectorAll方法通過 CSS 選擇器獲取元素。
// jquery code
document.querySelectorAll('.hello[type="checkbox"]').forEach(el => {
el.addEventListener('change', function() {
this.parentNode.querySelectorAll('.hello[type="checkbox"]').forEach(el1 => {
if (el !== el1) el1.checked = false;
});
});
});
<div>
<span>Group 1:</span>
<input type="checkbox" class="group1 hello" />
<input type="checkbox" class="group1 hello" />
<input type="checkbox" class="group1 hello" />
</div>
<div>
<span>Group 2:</span>
<input type="checkbox" class="group2 hello" />
<input type="checkbox" class="group2 hello" />
<input type="checkbox" class="group2 hello" />
</div>
<div>
<span>Group 3:</span>
<input type="checkbox" class="group3 hello" />
<input type="checkbox" class="group3 hello" />
<input type="checkbox" class="group3 hello" />
</div>
僅供參考:您可以使用單選按鈕實現相同的行為,而無需任何額外的 Javascript 代碼,只需為組提供相同的名稱屬性。
<div>
<span>Group 1:</span>
<input type="radio" name="group1" class="group1 hello" />
<input type="radio" name="group1" class="group1 hello" />
<input type="radio" name="group1" class="group1 hello" />
</div>
添加回答
舉報