在 class 末尾添加 +1

Adding +1 in the end of the class

我最近在空闲时间学习JavaScript/JQuery。我正在尝试让脚本在 2 个复选框之间进行选择。如果第一个复选框为真则第二个为假,如果第一个为假则第二个为真。这个有效,但不适用于多个 类。我添加了 2 类 .checkbox-group1 和 .checkbox-group2。我试图让脚本将 +1 添加到 .checkbox-group 2 次,但它只会添加所以我会得到 类 .checkbox-group1 和 .checkbox-group2 但我只得到 .checkbox-group1.

Javascript/JQuery

$(document).ready(function(){
    
    var i = 0;

if(i<2){

i++;

}

else{

i = 1;

}
    
    $('.checkbox-group'+ i +' input:checkbox').click(function() {
    $('.checkbox-group'+ i +' input:checkbox').not(this).prop('checked', false);
    });
});

HTML 复选框

<div class="checkbox-group1 required">
Yes: <input type="checkbox">
No: <input type="checkbox">
</div>


<div class="checkbox-group2 required">
yes: <input type="checkbox">
No: <input type="checkbox" >
</div>

您不需要循环,您可以在 var 中获取正确的复选框,然后将 div 的所有复选框设置为 false。最后,您将正确的设置为选中。

我评论了我的代码。

$(document).ready(function(){
    // we get div with class name starting like : checkbox-group
    $("div[class^='checkbox-group'],div[class*='checkbox-group']").click(function(event) {
      // we save current clicked element in a var
      var getCurrentChecked = event.target; 
      // we set all input checked to false
      $(this).find('input:checkbox').prop('checked', false);
      // then we check the right one
      $(getCurrentChecked).prop('checked', true);
      
      console.log($(this).attr('class') + ' - ' + $(getCurrentChecked).val());
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML CHECKBOXES

<div class="checkbox-group1 required">
Yes: <input type="checkbox" value="0">
No: <input type="checkbox" value="1">
</div>


<div class="checkbox-group2 required">
yes: <input type="checkbox" value="0">
No: <input type="checkbox" value="1">
</div>