我可以更改除toCity
之外的所有其他字段的ID。我克隆它时如何更改其ID?使用我当前的代码,下拉列表使用相同的数据创建,但ID保持不变。
克隆时如何更改ID?
var toAddCloneCount = 1;
function AddDestination() {
var clone = $("#toAdd").clone(true);
clone.find("#days").prop('id', 'days' + toAddCloneCount);
clone.find("#toDate").attr('id', 'toDate' + toAddCloneCount);
clone.find('#toCity').prop('id', 'toCity' + toAddCloneCount);
clone.show();
clone.attr('id', 'toAdd' + toAddCloneCount++).insertAfter("#toAdd");
clone.appendTo("#destinations");
}
<div id="destinations">
<div id="toAdd">
<table style="width: 100%;">
<tr>
<td class="auto-style8">To </td>
<td>
<select runat="server" id="toCity" name="toCity"></select>
</td>
<td>Days to Stay</td>
<td>
<input id="days" type="number" min="1" onkeypress="return false" onkeydown="return false" />
</td>
<td>
<p>
Date:
<input id="toDate" type="text" class="getCurrentDate" onkeypress="return false" onkeydown="return false" />
</p>
</td>
<td>
<button type="button" onclick="AddDestination();" >Add+</button>
</td>
</tr>
</table>
</div>
</div>
答案 0 :(得分:0)
var source = document.getElementById('id_here');
var options = source.innerHTML;
var copy = document.createElement("Select");
copy.id = "copy_id"
copy.innerHTML = copy.innerHTML + options;
document.body.appendChild(copy);
答案 1 :(得分:0)
你可以生成新的id&amp;元素名称:
$("button").click(function () {
var num = ($("div[id^='cloneItem_']").length + 1);
//alert(num);
$("#cloneItem_1").clone().insertAfter($("div[id^='cloneItem_']").last()).attr("id", 'cloneItem_' + num).find("select").each(function () {
$(this).prop({
'id': function (_, id) {
id = id.substring(0, id.indexOf('_') + 1);
return id + num;
},
'name': function (_, name) {
name = name.substring(0, name.indexOf('_') + 1);
return name + num;
},
'value': ''
});
});
});
转到小提琴演示:clone select element