[英]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.