我正在制作申请表。除了 PI 和表格提交者之外,还需要列出研究小组的成员。但是,有些研究没有其他团队成员,因此我希望该行保持隐藏状态,直到有人单击“添加团队成员”按钮。
什么在起作用: 1. 我在最初加载页面时隐藏了该元素。 2. 单击添加行添加正确的行。 3. 单击“删除”将删除一行。
目前的问题: 1. 如果有人添加了团队成员,然后删除了所有团队成员,则单击添加团队成员不会添加行。 2. 当该元素在初始页面加载时隐藏时,第一次单击“添加团队成员”按钮时会添加两行。
这是我当前的代码,仅包含表单的相关部分。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="assets/css/test.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function addTableRow(jQtable){
jQtable.each(function(){
var tds = '<tr>';
jQuery.each($('tr:last td', this), function() {tds += '<td>'+$(this).html()+'</td>';});
tds += '</tr>';
if($('tbody', this).length > 0){$('tbody', this).append(tds);
}else {$(this).append(tds);}
});
}
</script>
<script>
function myDeleteFunction() {
document.getElementById("stmember").deleteRow(0);
}
</script>
<script type="text/javascript">
$(function() {
$('#add').click(function() {
$('#stmember').show();
});
});
</script>
<style>
#stmember {
display: none
}
</style>
</head>
<body>
<h3><strong>Other Study Team Members:</strong></h3>
<FORM>
<table id="stmember">
<tr>
<td>Name:
<label for="namest1"></label>
<input type="text" name="namest1" id="namest1" placeholder="First Name, Last Name" />
</td>
<td>JHED ID:
<label for="jhedst1"></label>
<input type="text" name="jhedst1" id="jhedst1" />
</td>
<td>Email:
<label for="emailst1"></label>
<input type="email" name="emailst1" id="emailst1" placeholder="you@example.com" />
</td>
</tr>
</table>
<CENTER>
<button type="button" id="add" onclick="addTableRow($('#stmember'));">Add Study Team Member</button>
<button type="button" onclick="myDeleteFunction()">Remove Study Team Member</button>
</CENTER>
</FORM>
</body>
</HTML>
最佳答案
这里有一些适合您的解决方案:
解决方案1
将 addTableRow 函数中的行的 HTML 存储在变量中。这样您就可以使用输入 ID 的 token 来确保它们是唯一的。此外,您不必在 HTML 中提供第一行,因为它将通过 JS 函数创建。像这样的东西:
var template = "<tr><td>Name:<label for="namest1"></label><input type="text" name="namest!!TOKEN!!" id="namest!!TOKEN!!" placeholder="First Name, Last Name" /></td><td>JHED ID:<label for="jhedst1"></label><input type="text" name="jhedst!!TOKEN!!" id="jhedst!!TOKEN!!" /></td><td>Email:<label for="emailst1"></label><input type="email" name="emailst!!TOKEN!!" id="emailst!!TOKEN!!" placeholder="you@example.com" /></td></tr>";
解决方案2
使用类似 jsRender 的模板引擎或Mustache .
结论
如果您愿意的话,最干净的方法是使用模板引擎。但是使用字符串在函数中存储模板是可行的。
关于javascript - 最初隐藏然后动态添加和删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44576027/