javascript - 全局计数器变量

标签 javascript jquery

我有一段代码可以动态添加和删除表单控件。添加和删​​除方法工作正常。但我喜欢如果只存在一个控件,而不是删除它。

我在 $(document).ready 范围之外定义了下一个变量:

var Alumnos = {};

并在 $(document).ready 内部初始化:

// 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 值在删除后仍然存在。有什么想法吗?

更新 1

当用户点击“添加更多”时,代码从原型(prototype)创建一个包含 3 个控件的表单行。 因为,我不能使用 child 计数。 我需要用户不要删除所有控件。

最佳答案

我认为你应该:

 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

希望这对您有所帮助。干杯

关于javascript - 全局计数器变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21011527/

相关文章:

javascript - 为什么在这段 JavaScript 代码中函数调用发生在变量 x 递增之后

javascript - Jqgrid更新一列的所有行

c# - 在第一个下拉列表中选择后自动填充第二个下拉列表项

javascript - 如何在按键时使用 jQuery 获取文本框的值

javascript - 在滚动问题上向下滑动菜单

javascript - 从 html 字典属性中获取所有值

javascript - 如何在单击按钮时隐藏表单

javascript - CSS 表 : How to position action buttons left to each row

javascript - iOS 上 Sygic 的自定义架构的奇怪行为

javascript - 按行而非字符 chop 段落