Javascript 全局计数器变量
im有一个动态添加和删除表单控件的代码。添加和删除方法工作正常。但我喜欢只存在一个控件,而不是删除它 我在$(文档)之外定义了下一个var。就绪范围: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
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;
});