2009-10-26 9 views
2

중첩 된 정렬되지 않은 목록이 있고 부모 이벤트에 클릭 이벤트를 넣으므로 모든 자식 확인란을 선택하고 그 반대의 경우에도 확인란을 선택합니다. 어떤 이유로 나는 셀렉터를 타입 체크 박스의 모든 입력을 얻는 것만으로 얻을 수있다. 필자는 다양한 방법으로 시도했는데, 이것도 그 중 하나이다. 어떤 제안?jQuery 탐색 부모 및 자식

<ul id="parent"> 
<li> 
    <input type='checkbox'>first</input> 
    <ul> 
     <li><input type='checkbox'>child1</input> 
     </li> 
     <li><input type='checkbox'>child2</input> 
     </li> 
    </ul> 
</li> 

<li> 
    <input type='checkbox'>second</input> 
    <ul> 
     <li><input type='checkbox'>child1</input> 
     </li> 
     <li><input type='checkbox'>child2</input> 
     </li> 
    </ul> 
</li> 

</ul> 

jQuery를이

$('#parent > li input[type=checkbox]').click(function() { 

      var parent = $(this); 

      if ($(parent).is(':checked')) { 
       $('li > input[type=checkbox]', parent).each(function() { 
        $(this).attr('checked', true); 
       }); 
      } 
      else { 
       $('li > input[type=checkbox]', parent).each(function() { 
        $(this).attr('checked', false); 
       }); 
      } 
     }); 

답변

6

이 작동합니다 :

먼저 당신이 LI로 돌아가서 당신은 체크 박스를 검색보다

$('#parent > li input[type=checkbox]').click(function() { 

    $(this).closest("li").find("ul li input[type=checkbox]").attr('checked', $(this).is(':checked')) 

}); 

당신은 몇 가지를 추가하는 것이 좋습니다 그러나 클래스 이름. 그러면 코드가 읽기 쉽습니다. 당신의 jQuery를보다

<li> 
    <input type='checkbox' class='category'>first</input> 
    <ul> 
     <li><input type='checkbox' class='subcategory'>child1</input> 
     </li> 
     <li><input type='checkbox' class='subcategory'>child2</input> 
     </li> 
    </ul> 
</li> 

은 다음과 같이 보일 것이다 :

$("#parent .category").click(function(){ 

    $(this).closest("li").find(".subcategory").attr('checked', $(this).is(':checked')) 

}); 
+0

확실히 훌륭한 제안이다 클래스를 추가합니다. 감사합니다! – Gabe