2014-06-16 27 views
0

我有一個buildTree();函數,在嵌套的UL中構建LI中的複選框。最外面的UL被包裹在div#樹內。檢查div中的任何兩個複選框

HTML

<div id="tree"> 
    <ul> 
     <li class="speed parent-list"> 
      <input type="checkbox" name="speed" id="speed">speed<span class="glyphicon glyphicon-chevron-up"></span> 
      <ul class="speed" style="display: block;"> 
      <li class="hor_speed"><input type="checkbox" name="hor_speed" id="hor_speed">hor_speed</li> 
      <li class="ver_speed"><input type="checkbox" name="ver_speed" id="ver_speed">ver_speed</li> 
      <li class="heading"><input type="checkbox" name="heading" id="heading">heading</li> 
      </ul> 
     </li> 
     <li class="health"><input type="checkbox" name="heading" id="heading">health</li> 
     <li class="battery_level"><input type="checkbox" name="heading" id="heading">battery_level</li> 
    </ul> 
</div> 

我希望所有其他複選框被禁用,一旦樹中的任意兩個複選框被選中。到目前爲止,我已經做了這麼多,但它不起作用。

JS

buildTree(); 

var checkboxes = $('#tree [type=checkbox]'); 

checkboxes.change(function(){ 
    if(checkboxes.filter(':checked').length === 2){ 
    checkboxes.filter(':not(:checked)').prop('disabled',true); 
    } 
    else { 
    checkboxes.prop('disabled',false); 
    } 
}); 

UPDATE 代碼工作完美的,如果我把渲染樹直接在HTML文件,但一旦它使用jQuery呈現,這是行不通的。

+1

你今天早些時候問過類似的問題嗎?這看起來像是其中一個答案。 – Barmar

+0

似乎工作:[小提琴](http://jsfiddle.net/aGVxT/) –

+0

嗯,這不是你。你知道拉吉嗎? http://stackoverflow.com/questions/24240621/disable-other-checkboxes-if-two-of-them-are-selected-using-jquery#24240710 – Barmar

回答

1

看起來您正在動態加載內容,您需要事件委託來將事件附加到動態添加的DOM。就像這樣:

$('#tree').on('change','[type=checkbox]',function(){ 
if($('#tree [type=checkbox]').filter(':checked').length === 2){ 
    $('#tree [type=checkbox]').filter(':not(:checked)').prop('disabled',true); 
} 
else { 
    $('#tree [type=checkbox]').prop('disabled',false); 
}}); 
相關問題