为了账号安全,请及时绑定邮箱和手机立即绑定

根据 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 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信