所以我尝试使用 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>
这是我的 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>'; }
这里可能有点杂乱无章,但这里有一个指向代码 http://jsfiddle.net/2t9Dh/357/ 的 JSFiddle 的链接。 .这可能是一个非常简单的错误,如果有人能看到我的问题并帮助我,那就太好了。提前致谢。
更新
我正在关闭函数,并更新 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>';
}
追加到最后
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>';
}
关于javascript - 使用 JavaScript 添加具有输入字段的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34885101/