gpt4 book ai didi

javascript - 全局计数器变量

转载 作者:行者123 更新时间:2023-11-30 17:41:27 25 4
gpt4 key购买 nike

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

我在 $(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com