根据 html 将 jQuery 代码转换为 javascript

我有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>


潇湘沐
浏览 62回答 1
1回答

慕丝7291255

您可以querySelectorAll使用 CSS 选择器使用方法来获取元素。// jquery codedocument.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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5