2013-06-25 56 views
1

我試圖實現切換複選框,在這裏當我檢查/取消選中時,所有子複選框應該被選中/取消選中,我試圖在下面recurrsive樹補充的是樹的HTML的部分片斷檢查/取消選中所有兒童複選框應該在遞歸樹中切換(選中/取消選中)

<strong id="img_18" class="cat_minus" onclick="getchildcategories();"></strong> 
<input id="checkbox_18" type="checkbox" onclick="getchildcategories();" value=""> 
Apparel 
<ul> 
    <li> 
     <strong class="space_filler"></strong> 
     <input id="checkbox_4" type="checkbox" name="product_filter[ProductId][]" onclick="getchildcategories();"> 
     Shirts 
    </li> 
    <li id="category_5"> 
     <strong id="img_5" class="cat_plus" onclick="getchildcategories();"></strong> 
     <input id="checkbox_5" type="checkbox" name="product_filter[ProductId][]" onclick="getchildcategories();"> 
     Shoes 
    </li> 
    <li> 
     <strong class="space_filler"></strong> 
     <input id="checkbox_19" type="checkbox" name="product_filter[ProductId][]" onclick="getchildcategories();"> 
     Hoodies 
    </li> 
</ul> 

在上面的html我試圖說whecn我查身份證checkbox_18的chechbox比所有的孩子複選框應檢查/ uncheked(切換)

回答

1

使用您的HTML

<strong id="img_18" class="cat_minus" onclick="getchildcategories();"></strong> 
<input id="checkbox_18" type="checkbox" onclick="getchildcategories();" value=""> 
Apparel 
<ul> 
    <li> 
     <strong class="space_filler"></strong> 
     <input id="checkbox_4" class="childof_18" type="checkbox" name="product_filter[ProductId][]" onclick="getchildcategories();"> 
     Shirts 
    </li> 
    <li id="category_5"> 
     <strong id="img_5" class="cat_plus" onclick="getchildcategories();"></strong> 
     <input id="checkbox_5" class="childof_18" type="checkbox" name="product_filter[ProductId][]" onclick="getchildcategories();"> 
     Shoes 
    </li> 
    <li> 
     <strong class="space_filler"></strong> 
     <input id="checkbox_19" class="childof_18" type="checkbox" name="product_filter[ProductId][]" onclick="getchildcategories();"> 
     Hoodies 
    </li> 
</ul> 

如果你可以添加一個類到上面的子複選框,那麼你可以在任何觀察者處理程序中輕鬆地控制它們。對於實例

$('checkbox_18').observe('click',function(){ 
    //this is the element the event happened on 
    //in this case the element with id checkbox_18 
    if(this.checked) 
    { 
     $$('.childof_18').invoke('writeAttribute','checked','checked'); 
    } 
    else 
    { 
     $$('.childof_18').invoke('writeAttribute','checked',null); 
    } 
}); 

如果你不能在一個類添加到子複選框 - 但你知道DOM結構將是一致的,你可以使用DOM遍歷方法到那裏。這是我的方式。

$('checkbox_18').observe('click',function(){ 
    if(this.checked) 
    { 
     this.next('ul').select('input[type="checkbox"]').invoke('writeAttribute','checked','checked'); 
    } 
    else 
    { 
     this.next('ul').select('input[type="checkbox"]').invoke('writeAttribute','checked',null); 
    } 
}); 

警告:如果你的結構是與HTML代碼段保持一致您提供即父母旁的複選框包含子複選框一個<ul>到第2個方法纔有效。

相關問題