可以'单击主复选框时,不要更改所有复选框的css

Can't change css of all checkboxes when clicked on main checkbox

本文关键字:复选框 css 单击 可以      更新时间:2023-09-26

你好,伙计们,

我正在尝试用jQuery更改表单中所有复选框的背景和颜色。我不能让它工作。

这就是我的代码现在的样子:
HTML部分:

<form action="" method="">
    <div id="child1">
        <input type="checkbox" class="select-all-checkboxes" name="select-all-checkboxes" />
    </div>
    <div id="child2">
        <input type="checkbox" name="checkboxs[]" />
        <input type="checkbox" name="checkboxs[]" />
        <input type="checkbox" name="checkboxs[]" />
        <input type="checkbox" name="checkboxs[]" />
    </div>
</form>

jQuery部分

$('form input.select-all-checkboxes:checkbox').live('click', function()
{
    if($(this).attr('checked') == true)
    {
        $(this).parent('form').children('input:checkbox').css({
            background: 'rgba(0, 255, 0, 0.5)',
            border: '1px solid green'
        });   
    }
    else
    {
        $(this).parent('form').children('input:checkbox').css({
            background: 'none',
            border: '1px solid transparent'
        });   
    }
});

它应该做的是,当你点击类"选择所有复选框"的复选框时,表单中的所有复选框都应该被选中,并获得不同的边框和背景。

我就是没办法。希望你们能帮助我。

提前感谢,
标记

您的选择器错误。您需要使用parentsfind。即便如此,样式规则似乎对chrome中的复选框没有影响

$(this).parents('form').find('input:checkbox')

父级不是输入的直系祖先。您可能想将对children((的调用更改为对find((的呼叫。

http://api.jquery.com/find/

HTML:

<form action="" method="">
<div id="child1">
    <input type="checkbox" class="select-all-checkboxes" name="select-all-checkboxes" />
</div>
<div id="child2">
    <input type="checkbox" class= 'child_box' name="checkboxs[]" />
    <input type="checkbox" class= 'child_box' name="checkboxs[]" />
    <input type="checkbox" class= 'child_box' name="checkboxs[]" />
    <input type="checkbox" class= 'child_box' name="checkboxs[]" />
</div>
</form>

CSS:

 .greenbox{outline:#00ff00 solid 2px;}

jQuery:

$(function(){
  $('.select-all-checkboxes').click(function(){
    $(this).parent().parent().find('.child_box').attr('checked', this.checked);
    if (this.checked == true){
      $(this).parent().parent().find('.child_box').addClass('greenbox');   
    }else{
      $(this).parent().parent().find('.child_box').removeClass('greenbox');  
    }
  });
});

你尝试过吗:

$(".选择所有复选框"(.单击(function(({