【发布时间】:2015-11-01 23:54:45
【问题描述】:
基本上我想复制表单,但我希望它们具有不同的 ID。我还将使用表单中输入的值,因此它们的 ID 必须或多或少相似。因此,一种形式的 id 为“formA”,下一种形式为“formB”。我的同事建议在 IDS 中附加一个 int 值。这就是我所做的
var FormCounter = 1;
function addForms() {
// When the element '#addForm' is clicked then the forms are appended to the formContainer div
$("#addForm").click(function() {
/*
Note: you can add as many forms as you want and each will have a different ID.
Each ID will be unique as each ends with a different Integer.
*/
var formTitle = "<p> Form " + formCounter + "</p>";
// declare your form types here
var formType = "<input type='textField' id='textField" + formCounter + "'</input>";
// append to the formContainer div
$("#formContainer").append(formTitle);
// create a form tag
$("#formContainer").append("<form>");
/*
INSERT FORMS HERE
*/
$("#formContainer").append(formType);
// close form tag
$("#formContainer").append("</form>");
// insert a horizontal line
$("#formContainer").append("<hr>");
++formCounter;
});
}
我目前将此代码与一个文本字段一起使用。有没有其他方法可以做到这一点?之后我要做的是获取在字段中输入的值,然后将它们显示在表格上。
【问题讨论】:
-
考虑这里是否真的需要一个 id - 如果你是在 JavaScript 中创建它,那么你可以很容易地在创建时间。另请注意,在 jQuery 中分别附加打开和关闭标记可能与您预期的不同
标签: javascript jquery