[英]bugs in javascript
这里有两个我无法弄清的意外错误。
通用代码帮助随时欢迎您! 谢谢...
<div class="cloned" id="div1">
<input type="text" id="_name" name="1_name" placeholder="Field Name" required>
<input type="text" id="_hint" name="1_hint" placeholder="Hint">
<select id="_fieldtype" name="1_fieldtype" required>
<option value="">Field Type...</option>
<option value="bla">bla</option>
<option value="blabla">blabla</option>
</select>
<input type="checkbox" id="_required" name="1_required" value="true"> Required
<input type="checkbox" id="_search" name="1_search" value="true"> Searchable
<input type="checkbox" id="_editable" name="1_editable" value="true"> Editable
<input type="radio" id="_label" name="label" value="1_label"> Label
<input type="radio" id="_unique" name="unique" value="1_unique"> Unique
<input type="button" class="add" value="+">
<input type="button" class="remove" value="-">
</div>
<script>
function addDiv(){
window.num = $('.cloned').length;
var num = $('.cloned').length;
var newnum = num + 1;
var newelem = $('#div'+num).clone().attr('id','div'+newnum);
$.each(newelem.children(), function(){
if (this.type == 'radio'){
$(this).attr('value',newnum+this.id).removeAttr('checked')
}
else if (this.type == 'button'){
$(this).removeAttr('checked')
}
else if (this.type != 'button'){
$(this).attr('name',newnum+this.id).attr('value','')
}
});
$('#div'+num).after(newelem);
};
function removeDiv(object){
window.num = $('.cloned').length;
if (num != 1)
$(object.parentNode).remove();
};
$('.add').live('click', function(){
addDiv();
});
$('.remove').live('click', function(){
removeDiv(this);
});
</script>
对于第二个问题,您需要重复按下按钮,将代码更改为
else if (this.type == 'checkbox' || this.type == 'radio'){
$(this).removeAttr('checked')
}
删除div的问题是,当您删除第一个div并尝试克隆一个新的div时,您仍在寻找第一个div,即ID为div1的div要克隆,但是找不到。.这是您很奇怪的原因处理数字..而是始终始终保存div的隐藏副本,并使用相同的隐藏div对其进行克隆,因此您不必担心清除内容,复选框等。它将处于默认状态。
这样你就会有
<div style="display:none" id="masterDiv">
<input type="text" id="_name" name="1_name" placeholder="Field Name" required>
<input type="text" id="_hint" name="1_hint" placeholder="Hint">
<select id="_fieldtype" name="1_fieldtype" required>
<option value="">Field Type...</option>
<option value="bla">bla</option>
<option value="blabla">blabla</option>
</select>
<input type="checkbox" id="_required" name="1_required" value="true"> Required
<input type="checkbox" id="_search" name="1_search" value="true"> Searchable
<input type="checkbox" id="_editable" name="1_editable" value="true"> Editable
<input type="radio" id="_label" name="label" value="1_label"> Label
<input type="radio" id="_unique" name="unique" value="1_unique"> Unique
<input type="button" class="add" value="+">
<input type="button" class="remove" value="-">
</div>
并总是克隆它。
总的来说,还有另一件事是尽可能避免使用全局变量。.您永远都不知道最终会改变它。
确实,您应该将模型与视图分开。 您不仅不必进行任何这些检查,而且您在进行检查的事实意味着可以改进您的结构。
参见小提琴: http : //jsfiddle.net/cnJa9/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.