2014-01-09 111 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; 
});