2011-12-02 69 views
1

我正在創建一個使用jquery複選框的json樹。這裏是我的代碼:jquery樹選擇所有兒童複選框

<body> 
    <div id="regionTree"> 

    </div> 

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> 
    </script> 
    <script> 
    $(function(){ 

     var json = [{"ID":1,"Name":"r1","Child":[{"ID":1,"Name":"c1"},{"ID":2,"Name":"c2"}]},{"ID":1,"Name":"r2","Child":[{"ID":1,"Name":"c1"},{"ID":2,"Name":"c2"}]}]; 
     //debugger; 
     var treeString = ''; 
     treeString+='<ul>'; 
     $(json).each(function(key, value) { 
      treeString+='<li>'; 
      treeString+='<label><input type="checkbox" class="parent"/>'+value.Name+'</label><br/>'; 
      //alert(value.Name); 
      if(value.Child != undefined && value.Child.length > 0) 
      { 
       treeString+='<ul>'; 
       $(value.Child).each(function(key,value){ 
        treeString+='<li>'; 
        treeString+='<label><input type="checkbox" class="child"/>'+value.Name+'</label><br/>'; 
        treeString+='</li>'; 
        //alert(value.Name); 
       }); 
       treeString+='</ul>'; 
      } 
      treeString+='</li>'; 
     }); 
     treeString+='</ul>'; 
     $('#regionTree').append(treeString); 

     //------ 
     $('.parent').live('click', function(){ 
      debugger; 
      console.log($(this).find('.child').size()); 
      $(this).parent().children(':checkbox').prop("checked", true); 

     }); 
    }); 
    </script> 
</body> 

如果你複製粘貼並在FF/Chrome中打開,你可以看到複選框樹。如果選擇父項,我想選擇一個節點的所有子元素。但由於某種原因,我無法獲取節點的所有子選框。

請幫忙。

回答

0
$(this).parent().children(':checkbox').prop("checked", true); 

複選框的父標籤,而不是李。

嘗試:

$(this).closest('li').find(':checkbox').prop("checked", true); 
+0

啊!! @Anyd工作正常.. :) – Amit