2008-10-01 59 views
2

你能做一個更好的代碼嗎?我需要根據父母檢查/取消選中所有孩子,當孩子被選中時,檢查父母,當所有孩子未選中時取消選中父母。檢查/取消選中父母和孩子

$(".parent").children("input").click(function() { 
    $(this).parent().siblings("input").attr("checked", this.checked); 
}); 

$(".parent").siblings("input").click(function() { 
    if (this.checked) { 
     $(this).siblings("div").children("input").attr("checked", true); 
     return; 
    } 

    var childs = $(this).siblings("div").siblings("input"); 

    for (i = 0; i < childs.length; i++) { 
     if ($(childs.get(i)).attr("checked")) 
      return; 
    } 

    $(this).parent().children("div").children("input").attr("checked", false); 
}); 

回答

1
$(".parent").children("input").click(function() { 
    $(this).parent().siblings("input").attr("checked", this.checked); 
}); 

$(".parent").siblings("input").click(function() { 
    $(this).siblings("div").children("input").attr("checked", 
     this.checked || $(this).siblings("input[checked]").length>0 
    ); 
}); 
+0

做什麼是「.siblings(...)。兄弟姐妹(...)」?還有:「$(this).parent()。children(...)」可能就是「.siblings(...)」 – nickf 2008-10-02 02:52:40

1

哇,我是超級困惑。它看起來好像你有其他輸入內的輸入? ......這沒有意義。這裏是我的認爲你的結構看起來像,所以我在這裏。

<div class="parent"> 
    <input type="checkbox" /> 
    <div> 
     <input type="checkbox" /> 
     <input type="checkbox" /> 
    </div> 
    <input type="checkbox" /> 
    <div> 
     <input type="checkbox" /> 
     <input type="checkbox" /> 
    </div> 
</div> 

這裏是我使用的代碼。

$("input[type='checkbox']").click(function() { 
    // turn on or off all descendants. 
    $(this)   // get this checkbox 
     // get the div directly after it 
     .next('div') 
     // get ALL the inputs in that div (not just first level children) 
     .find("input[type='checkbox']") 
     .attr("checked", this.checked) 
    ; 

    // now check if we have to turn the parent on or off. 
    $(this) 
     .parent() // this will be the div 
     .prev('input[type="checkbox"]') // this is the input 
     .attr(
      "checked",  // set checked to true if... 
      this.checked // this one is checked, or... 
      || $(this).siblings("input[type='checkbox'][checked]").length > 0 
          // any of the siblings are checked. 
     ) 
    ; 
}); 

更新:我剛測試過這個,它完全工作(宇!)。它也適用於任意多層次的嵌套,而不僅僅是兩層。

0

這是一個可愛的小線程,讓我幾乎在我需要的地方。我稍微改編了Nickf的代碼。其目的是檢查一個孩子也會檢查父母,並取消選中父母也會取消所有孩子的檢查。

$( 「輸入[類型= '複選框']」)點擊(函數(){ 如果($(this.checked)){

$(this) 
    .next('div') 
    .find("input[type='checkbox']") 
    .attr("checked", this.checked) 
; 
} 


$(this) 
    .parent() 
    .prev('input[type="checkbox"]') 
    .attr("checked", this.checked || $(this).siblings("input[type='checkbox'][checked]").length > 0 

    ) 
; 

}!)。

如何調整這一點,以便所有的後代在未選中的情況下都未被選中?

全新的JQ和javascript..apologies。

0
$('.parent').click(function(){ 
    checkBox = $(this).find('input[type=checkbox]'); 
    checkBox.prop("checked", !checkBox.prop("checked")); // inverse selection 
}); 

終極。