这里有几个意想不到的错误,我无法弄清楚.
一般代码帮助随时欢迎!谢谢...
<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>
Run Code Online (Sandbox Code Playgroud)
对于您的第二个问题,您可以重复按钮将代码更改为
else if (this.type == 'checkbox' || this.type == 'radio'){
$(this).removeAttr('checked')
}
Run Code Online (Sandbox Code Playgroud)
删除div的问题是,当你删除第一个div并尝试克隆一个新的div时,你仍然在寻找第一个div,即id为div的div为克隆而且它无法找到..这是你的怪异的cos处理数字..而只是持有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>
Run Code Online (Sandbox Code Playgroud)
并始终克隆它.
通常还有一件事可以尽可能地避免全局变量.你永远不知道最终会改变它的是什么.
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |