有很多不同的方法可以做到这一点。我最近有一个项目,我必须做这件事。 Here is a working Fiddle以下代码示例:
HTML
<div id="container">
<span id="sholder"></span>
<br />
<input type="button" value="Add Section" class="addsection" />
</div>
<div id="section_template" class="template">
<div class="section">
<span class="taholder"></span>
<br />
<input type="button" value="Add Textarea" class="addtextarea" />
</div>
</div>
这里的关键概念是我创建了一个div 部分,其类为template,并且在CSS 中template 设置为display: none;。我稍后会在 CreateSection() 函数中使用它来更轻松地创建更大的 HTML 部分。
jQuery / javascript
$(function() {
//add the click handler to add a new section
$("input.addsection").click(CreateSection);
//add the click handler for the new section
//since the buttons are added dynamically, use "on" on the "document" element
// with the selector for the button we want to watch for.
$(document).on("click", "input.addtextarea", function() {
var section = $(this).closest("div.section");
AddTextarea(section);
});
});
function CreateSection() {
var section = $("#section_template div.section").clone();
var holder = $("#container span#sholder");
//get the current total number of sections
var sectionCount = holder.find("div.section").length;
//create the section id by incrementing the section count
section.attr("id", "section" + (sectionCount + 1));
//add a textarea to the section
AddTextarea(section);
//add the new section to the document
holder.append(section);
}
function AddTextarea(section) {
var sectionID = section.attr("id");
var holder = section.find("span.taholder");
//get the current total number of textareas in this section
var taCount = holder.find("textarea").length;
//create the new textarea element
var ta = $(document.createElement("textarea"));
//create the textarea unique id
var taID = section.attr("id") + "_textarea" + (taCount + 1);
ta.attr("id", taID);
//show the id... can be removed
ta.val("ID: " + taID);
//add the textarea to the section
holder.append(ta);
}
以上代码中有几个有用的搜索功能:closest、find。另外,我正在使用 clone 函数来复制该 HTML 部分。
另外值得注意的是,我使用$(document.createElement("textarea")) 创建了新的textarea。 document.createElement 是fastest way for JS to create new HTML DOM objects。
还有一些 CSS 示例
div.template {
display: none;
}
div.section {
border: 1px solid black;
}
div.section textarea {
display: block;
}
如您在 JSFiddle 中所见,此示例保持 ID 的唯一性。但是,如果将这些字段发布到服务器,则阅读这些字段是对另一个问题的回答。