2014-01-09 108 views
1

即時通訊有一個代碼,添加和刪除動態窗體控件。添加和刪​​除方法工作正常。但我喜歡如果只存在一個控件,而不是刪除它。全局計數器變量

予定義的下一個變種,外$(文件)。就緒範圍:

var Alumnos = {}; 

並初始化內部的(文檔)$。就緒:

// Valor inicial de casilleros renderizados. 
Alumnos.count = 3; 

該刪除控件是方法:

// Elimina un bloque 
$(document).on('click','.closable',function(){ 
    if(Alumnos.count > 1){ 
     var idRow = $(this).attr('data-toggle'); 
     var victim = $(idRow + " .row-fluid:last-child"); 
     victim.remove(); 

     var childs = $(idRow).children(); 
     if(childs.length === 0) 
     { 
      $(idRow).remove(); 
      $(this).remove(); 
      Alumnos.count -= 1; 

     } 
    } 
    console.log(Alumnos.count); 
    return false; 
}); 

刪除後,Alumnos.count值仍然存在。有任何想法嗎 ?

UPDATE 1

當用戶通過點擊「添加更多」,代碼,創建一個表格行與3所控制,從一個原型。 因爲,我不能使用兒童數。 我需要用戶不要刪除所有控件。

+1

移動'Alumnos.count - = 1;''以上如果(childs.length === 0)' –

+0

可能'如果(childs.length === 0)condition'未給出TRUE; ,你可以創建一個在線演示你的代碼。 –

回答

2

我想你應該有:

if(Alumnos.count >= 1){ //Probably if there is only 1, it's erasable. You had > 

而且之外將遞減,就像這樣:

var childs = $(idRow).children(); 
    if(childs.length === 0) 
    { 
     $(idRow).remove(); 
     $(this).remove();    
    } 
    Alumnos.count -= 1; //This was moved 

希望這有助於。乾杯

+0

如果OP想要在刪除元素idRow後遞減計數,那麼? –

+0

可能或者可能在刪除「受害者」時 –

0

感謝您的回覆!我發現控制元素刪除的方式與孩子數量。可能不是最好的代碼,但工作。

$(document).on('click','.closable',function(){ 

    // Get the id of the row. 
    var dataToggle = $(this).attr('data-toggle'); 
    // Get the row 
    var row = $(dataToggle); 

    // if isnt first row (#id0), ok, remove all if you want. 
    // if is first row (#id0) and have more than one child, happy remove ^^ 
    if((dataToggle === "#id0" && row.children().length > 1) || dataToggle !== "#id0"){ 

     // remove code... 
    } 

    return false; 
});