因此,我尝试使用JavaScript在表格行中添加额外的输入字段,但似乎无法弄清楚。我现在的方法是每次有人单击“添加更多”按钮时,仅插入额外的html代码并添加新的表格行。这是我的代码
的HTML
<div class="set-form">
<table class="table table-bordered">
<tr>
<th>Question</th>
<th>Answer</th>
</tr>
<tr>
<td>
<textarea name="Question" placeholder="Question" th:field="${questionAnswerSet.question}" id="question" style="resize: none; width: 100%;"></textarea>
</td>
<td>
<textarea name="Answer" placeholder="Answer" th:field="${questionAnswerSet.answer}" id="answer" style="resize: none; width: 100%;"></textarea>
</td>
</tr>
</table>
<div class="set-form">
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" />
</div>
Run Code Online (Sandbox Code Playgroud)
这是我的JavaScript
function add_fields() {
document.getElementById('set-form').innerHTML += '<tr> < td > < textarea name = "Question"
placeholder = "Question"
th: field = "${questionAnswerSet.question}"
id = "question"
style = "resize: none; width: 100%;" > < /textarea></td >
< td > < textarea name = "Answer"
placeholder = "Answer"
th: field = "${questionAnswerSet.answer}"
id = "answer"
style = "resize: none; width: 100%;" > < /textarea></td >
< /tr>'; }
Run Code Online (Sandbox Code Playgroud)
它可能在这里有些杂乱无章,但是这里是指向代码JSFiddle的链接http://jsfiddle.net/2t9Dh/357/。这可能是一个非常简单的错误,如果有人可以看到我的问题并帮助我,那就太好了。提前致谢。
更新
我正在关闭函数,并更新ID和类名
给出一个表,ID写在js代码下面。
<div class="set-form">
<table id="myTable" class="table table-bordered">
<tr>
<th>Question</th>
<th>Answer</th>
</tr>
<tr>
<td>
<textarea name="Question" placeholder="Question" th:field="${questionAnswerSet.question}" id="question" style="resize: none; width: 100%;"></textarea>
</td>
<td>
<textarea name="Answer" placeholder="Answer" th:field="${questionAnswerSet.answer}" id="answer" style="resize: none; width: 100%;"></textarea>
</td>
</tr>
</table>
<div class="set-form">
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" />
</div>
function add_fields() {
document.getElementById("myTable").insertRow(0).innerHTML = '<tr><td><textarea name="Question" placeholder="Question" th:field="${questionAnswerSet.question}" id="question" style = "resize: none; width:100%;"></textarea></td><td><textarea name="Answer" placeholder ="Answer" th: field="${questionAnswerSet.answer}" id="answer" style="resize:none;width: 100%;"></textarea></td ></tr>';
}
Run Code Online (Sandbox Code Playgroud)
追加到最后
function add_fields() {
document.getElementById("myTable").insertRow(-1).innerHTML = '<tr><td><textarea name="Question" placeholder="Question" th:field="${questionAnswerSet.question}" id="question" style = "resize: none; width:100%;"></textarea></td><td><textarea name="Answer" placeholder ="Answer" th: field="${questionAnswerSet.answer}" id="answer" style="resize:none;width: 100%;"></textarea></td ></tr>';
}
Run Code Online (Sandbox Code Playgroud)