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

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

根據 html 將 jQuery 代碼轉換為 javascript

根據 html 將 jQuery 代碼轉換為 javascript

慕哥9229398 2022-06-16 09:59:14
我有 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 中更改和添加屬性來嘗試此代碼,但它不適用于我的 questin 中的組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 回答

?
白衣非少年

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>


查看完整回答
反對 回復 2022-06-16
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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