到clone该字段集并将其添加到同一个父级:
var fieldset = $("#question1"); // Get the fieldset
var clone = fieldset.clone(); // Clone it
clone.attr("id", "question2"); // Set its ID to "question2"
clone.appendTo(fieldset.parent()); // Add to the parent
请注意,在将 ID 添加到树之前,我们是 changing,因为您不能有两个具有相同 ID 的元素。
要处理其中的元素,您可以在 clone 变量上使用 .children() 或 .find() 和选择器来选择您想要的子/后代(一旦您将克隆添加到父)。例如,清理输入上的ids:
clone.find('input').each(function() {
if (this.id) {
// It has an ID, which means the original had an ID, which
// means your DOM tree is temporarily invalid; fix the ID
this.id = /* ...derive a new, unique ID here... */;
}
});
请注意,在each 回调中,this 不是 jQuery 实例,它是原始元素。 (因此我直接设置this.id。)如果你想为元素获取一个jQuery实例,你会做var $this = $(this);然后使用$this.attr("id", ...)。但除非你做的不是改变 ID,否则没有特别的需要。
回答您关于重新编号 ID 的问题时,您需要确保更新使用这些 ID 的所有内容以及输入元素上的实际 ID。
但在对输入元素进行更新方面,您可以通过读取数字并将其递增直到获得未使用的数字:
clone.find('input').each(function() {
var id;
if (this.id) {
id = this.id;
do {
id = id.replace(/[0-9]+$/g, function(num) {
return String(Number(num) + 1);
});
}
while ($("#" + id).length > 0);
this.id = id;
}
});
...如果原始 ID 是“input_radio1”,它将为您提供“input_radio2”,但我想我可能会使用不同的命名约定。例如,您可以在各种输入 ID 前加上问题 ID:
<fieldset id='question1'>
...
<input id=-'question1:input_radio1' />
</fieldset>
...然后在克隆的 ID 中将“question1”替换为“question2”。 (冒号 [:] 在 ID 中完全有效。)
但是,如果您可以避免在所有输入中使用 ID,那将是可行的方法。例如,除非您的标记出于其他原因阻止它,否则您可以通过包含而不是使用 for 将 input 与其 label 关联:
<label>First name: <input type='text' ... /></label>
很多选择。 :-)