Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 全局计数器变量_Javascript_Jquery - Fatal编程技术网

Javascript 全局计数器变量

Javascript 全局计数器变量,javascript,jquery,Javascript,Jquery,im有一个动态添加和删除表单控件的代码。添加和删除方法工作正常。但我喜欢只存在一个控件,而不是删除它 我在$(文档)之外定义了下一个var。就绪范围: var Alumnos = {}; 并在$(文档)内初始化。准备就绪: 删除控件的方法是: // Elimina un bloque $(document).on('click','.closable',function(){ if(Alumnos.count > 1){ var idRow = $(this).a

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

我在$(文档)之外定义了下一个var。就绪范围:

var Alumnos = {};
并在$(文档)内初始化。准备就绪:

删除控件的方法是:

// 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

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

我认为您应该:

 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

希望这有帮助。干杯

谢谢您的回复!!我找到了通过childs计数控制元素移除的方法。可能不是最好的代码,但很有效

$(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;
});

move
Alumnos.count-=1如果(childs.length==0)
可能是
如果(childs.length==0)条件
没有给出
true
,您可以创建代码的在线演示。如果OP想要在删除元素idRow后减少计数,那么?可能是,或者可能是在删除
受害者时
$(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;
});