亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據 html 將 jQuery 代碼轉換為 javascript

根據 html 將 jQuery 代碼轉換為 javascript

瀟湘沐 2023-11-13 11:03:21
我有html和js代碼。但 javascript 代碼是由 jQuery 編寫的,我想將此 jQuery 代碼轉換為 Javascript:// jquery code$('.hello[type="checkbox"]').on('change', function() {   $(this).siblings('.hello[type="checkbox"]').not(this).prop('checked', false);});和我的 html 標記:<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>我想使用此代碼進行復選框輸入,我只想檢查用戶的一個輸入查看演示我通過在 html 中更改和添加屬性來嘗試此代碼,但它對于我的問題中的組無法正常工作function checkOnlyOne(b){var x = document.getElementsByClassName('daychecks');var i;for (i = 0; i < x.length; i++) {  if(x[i].value != b) x[i].checked = false;}}<div>    <span>Group 3:</span>    <input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />    <input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />    <input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); /></div>
查看完整描述

1 回答

?
慕絲7291255

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>


查看完整回答
反對 回復 2023-11-13
  • 1 回答
  • 0 關注
  • 144 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號