Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将类添加到已选中的复选框其他已删除的活动复选框_Javascript_Jquery_Html - Fatal编程技术网

Javascript 如何将类添加到已选中的复选框其他已删除的活动复选框

Javascript 如何将类添加到已选中的复选框其他已删除的活动复选框,javascript,jquery,html,Javascript,Jquery,Html,我有三个复选框。我只想为选中的复选框将类添加到父级li。其他我想删除活动类名或添加关闭的类名 HTML <ul> <li class="active"> <ul> <li> <input type="checkbox" class="level"/> <label>test1</label> </li>

我有三个复选框。我只想为选中的复选框将类添加到父级
li
。其他我想删除活动类名或添加关闭的类名

HTML

  <ul>
    <li class="active">
      <ul>
        <li>
          <input type="checkbox" class="level"/>
          <label>test1</label>
        </li>
      </ul>
    </li>
    <li class="closed">
      <ul>
        <li>
          <input type="checkbox" class="level"/>
          <label>test2</label>
        </li>
      </ul>
    </li>
    <li class="closed">
      <ul>
        <li>
          <input type="checkbox" class="level"/>
          <label>test3</label>
        </li>
      </ul>
    </li>
  </ul>
你可以用

$('.level')。在('click',函数(e)上{
var$ul=$(this).closest('ul').parent();
$ul.toggleClass('active',this.checked);
$ul.toggleClass('closed',!this.checked);
如果(选中此项){
$('.level').not(this).prop('checked',false.).closest('ul').parent().removeClass('active').addClass('closed');
}
});
.active{
颜色:绿色;
}
.关闭{
背景颜色:浅灰色;
}

    • 测试1
    • 测试2
    • 测试3

ToggleClass绝对是您想要的,但是如果您正确地连接了事件侦听器,您也不需要遍历dom来查找父列表项

相反,您可以使用委派目标:

//注意,我在main中添加了一个“top”类
    $('ul.top>li')。关于('change','input',函数(e){ //选择顶级
  • $(e.delegateTarget) //根据输入的“选中”状态切换活动/关闭类 .toggleClass('active',this.checked.).toggleClass('closed',!this.checked); });
    .top li:before{content:attr(class);}.active{font-weight:bold;color:green;}.closed{color:red;}
    
    
      • 测试1
          • 测试2
            • 测试3
            无需无线电。我只想使用复选框。我只想使用checkbox@user1175112很抱歉您的要求是什么?我只想勾选一个复选框,其他复选框未勾选three@user1175112因此,如果选中1个复选框,则必须取消选中上一个复选框?-你为什么不用无线电信箱来代替你可以用传真发送?
            $('.level').on('click', function(e) {
                if ($(this).attr('checked')) {
                    $(this).closest('ul').parent().addClass('active');
                } else {
                    $(this).closest('ul').parent().removeClass('active');
                }
            });