单击主复选框时无法更改所有复选框的css

时间:2011-12-02 19:46:07

标签: javascript jquery forms

大家好,

我正在尝试使用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'
        });   
    }
});

它应该做的是当你点击“select-all-checkboxes”类的复选框时,表格中的所有复选框都应该被检查并获得不同的边框和背景。

我只是不让它发挥作用。希望你们能帮助我。

先谢谢,
标记

4 个答案:

答案 0 :(得分:2)

你的选择器错了。您需要使用parentsfind。即便如此,样式规则似乎对chrome

中的复选框没有影响
$(this).parents('form').find('input:checkbox')

答案 1 :(得分:1)

父母不是投入的直接祖先。您可能希望将对children()的调用更改为对find()的调用。

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

答案 2 :(得分:1)

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');  
    }
  });
});

答案 3 :(得分:0)

你有没有尝试过:

$('。select-all-checkboxes')。click(function(){