我試圖通過添加和刪除輸入選項來動態構建input元素。 我也使用php從我的數據庫中動態構建下來。 當我添加輸入時,我痛苦數組中的父id,當我刪除輸入我使用拼接刪除它。我添加或刪除的每個框都包含幾個輸入jQuery store div parent id,並將其從數組中刪除
我將輸入成功添加到數組,併成功通過它們使用ajax,問題是當我刪除1輸入它刪除所有我的父母div如循環中。
var x = 1
var appleTestList;
var appleinputList = new Array();
$('#applePlus').click(function(e){ //on add input button click
var wrapper = $("#appleDinamicBox"); //Fields wrapper
; //initlal text box count
$.ajax({
async: false,
type: "GET",
url: "sqlFunctrions.php",
data: 'func=dropDownbyValue&table=test&value=Test_ID&display=Test_Name&column=Test_Type&valueBy=Apple&selectName=appleTest&chooseFrom=Test',
success: function(msg){
appleTestList=msg;
}
}); // Ajax Call
var htmlString='';
x++; //text box increment
htmlString=htmlString + '<div class="seperate" id="'+x+'"><div class="col-lg-5"><label>Test Name:</label>';
htmlString = htmlString + '<select name="appleTestName'+x+'" id="appleTestName'+x+'" class="form-control"><option value=\"0\">Test</option>' +appleTestList+'</select>';
htmlString = htmlString + '</div><div class="col-lg-5"><label>Namber Of Setups</label><input class="form-control" type="text" name="appleNumOfSetups'+x+'" id="appleNumOfSetups'+x+'"></div><img src="images/minus-s.png" id="appleMinus" class="remove_field"></div>';
$(wrapper).append(htmlString); //add input box
appleinputList.push(x);
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
var id = $(this).parent().attr('id');
alert(id);
appleinputList.splice(appleinputList.indexOf(parseInt(id)),1);
alert(id);
});
}
你可以我的錯誤,有任何其他的方式來做到這一點?
謝謝, Cfir。
可能是這行:$(this).parent('div')。remove(); – DeFeNdog 2014-09-10 17:55:51
我會在'.remove_field'元素中添加一個'data-targetid = x',並在處理程序中顯式地將其拉出('id = $(this).data('targetid')'),而不是使用父關係。 – Malk 2014-09-10 17:56:37
你有沒有考慮過使用像Knockout這樣的模板庫來構建動態視圖?這是值得檢查:http://knockoutjs.com/ – masterwok 2014-09-10 17:58:47