2010-01-22 109 views
1

基本上我正在尝试编写一个js func,如果我检查了子复选框,父复选框也会检查,如果尚未检查。我在这里使用jQuery是我的html:使用jQuery检查父复选框

 <ul id="ulParent" style="margin: 0; padding: 0; list-style: none;"> 
      <li style="margin: 0 0 5px 0;"> 
       <input type="checkbox" checked="checked" class="liParent" id="p1" />Parent1 
       <ul id="ulParent" style="margin: 0; padding: 0; list-style: none;"> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c1" onclick="checkParent(this);" />Child1 
        </li> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c2" onclick="checkParent(this);"/>Child2 
        </li> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c3" onclick="checkParent(this);"/>Child3 
        </li> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c4" onclick="checkParent(this);"/>Child4 
        </li> 
       </ul> 
      </li> 

      <li style="margin: 0 0 5px 0;"> 
       <input type="checkbox" checked="checked" class="liParent" id="p2" />Parent2 
       <ul id="ulParent" style="margin: 0; padding: 0; list-style: none;"> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c1" onclick="checkParent(this);" />Child1 
        </li> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c2" onclick="checkParent(this);"/>Child2 
        </li> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c3" onclick="checkParent(this);"/>Child3 
        </li> 
        <li> 
         <input type="checkbox" checked="checked" class="liChild" id="c4" onclick="checkParent(this);"/>Child4 
        </li> 
       </ul> 
      </li> 
</ul> 

JS Func键

function checkParent(child){ 

if (child != null) { 

    // if child is checked we need to check the parent category  
    if (child.checked) { 
    // get the parent checkbox and check it if not check....need help here.... 
      $(child).parent().parent().parent()...... 

     } 
    } 
} 
+0

你为什么要设置试图检查父复选框,当CSS颜色?这只是为了测试,看看选择器是否工作? – 2010-01-22 17:43:27

+0

仅用于测试:) – Gabe 2010-01-22 17:47:44

+0

您还需要更新输入控件。你应该在其中有属性type =“checkbox”。没有这个,大多数浏览器都无法正常工作。例如,FF3会将您当前的标记显示为所有文本框,而不是复选框。 – 2010-01-22 17:56:17

回答

2

我会删除内联的JavaScript在HTML和使用jQuery绑定来绑定检查事件:

$(document).ready(function() { 
    $('input.liChild').change(function() { 
     if ($(this).is(':checked')) { 
      $(this).closest('ul').siblings('input:checkbox').attr('checked', true); 
     } 
    }); 
}); 

这会将您正在查找的事件绑定到类liChild的任何输入,而无需使用所有这些onclicks。

+0

我认为你想最亲近,而不是父母。父母只会查找提升,而最接近的会继续前进,直到找到选择器。 – Mark 2010-01-22 17:52:29

+0

是的,刚才发现了,谢谢。 – Parrots 2010-01-22 17:54:42

+0

*最近*或*父母*将工作,因为*父母*获得祖先,但*父*只是获得父母,在这种情况下,父母不够高。虽然这样安排是个好主意。 – 2010-01-22 17:56:58

0

这将工作,根据您的结构:

$(child).parent().parent().prev().attr('checked', true);

$(child).closest('ul').prev().attr('checked', true);;

相关问题