我有使用JavaScript动态生成的输入.但是,我不确定如何向这些添加ID.让我说清楚:我想为每个人提供不同的ID,我知道如何为所有人添加一个id.
这就是我尝试过的:
$(document).ready(function() {
var wrapper = $(".wayptHolder"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 0; //initial text box count
//add input element
$(add_button).click(function(event){
event.preventDefault();
if(x < 8){
$(wrapper).append('<div><input type="text", id="waypt"' + x + ' class="form-control added-input", placeholder="Next"><a href="#" class="remove_field">Remove</a></div>');//add inputbox
x++;
}
});
$(wrapper).on("click",".remove_field", function(event){ //user click on remove text
event.preventDefault(); $(this).parent('div').remove(); x--;
})
});
Run Code Online (Sandbox Code Playgroud)
但是,在新元素上,它将id显示为waypt.我研究过,它看起来不像JavaScript有字符串插值.例如,Ruby可以解决这个问题,因为它能够使用#pt(#x),以便字符串将x解释为变量.JS如何复制这种行为?
您的双引号未正确关闭:
$(wrapper).append('<input type="text", id="waypt"' + x + ' class="...
Run Code Online (Sandbox Code Playgroud)
会产生以下HTML:
<input type="text", id="waypt" 0 class="...
<input type="text", id="waypt" 1 class="...
Run Code Online (Sandbox Code Playgroud)
显而易见的解决方案是修复引号(并删除逗号):
$(wrapper).append('<input type="text" id="waypt' + x + '" class="...
Run Code Online (Sandbox Code Playgroud)
但是,我建议像:
var $div = $("<div>");
$("<input>", {
"type": "text",
"id": "waypt" + x,
"class": "form-control added-input",
"placeholder": "Next"
}).appendTo($div);
$("<a></a>", {
"href": "#",
"class": "remove_field"
}).text("Remove").appendTo($div);
$div.appendTo(wrapper);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |