1 回答

TA貢獻1859條經驗 獲得超6個贊
您可以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>
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報