我有一段代码可以动态添加和删除表单控件。添加和删除方法工作正常。但我喜欢如果只存在一个控件,而不是删除它。
我在 $(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/