我有以下内容:
<table>
<tr><td>author's first name</td><td>author's last name</td></tr>
<tr><td><input type='text' name='first_name' /></td><td><input type='text' name='last_name' /></td></tr>
</table>
<a href='' onclick='return false;'>Add Author</a>
每次单击“添加作者”链接标记时,我都想创建一个额外的表格行,如下所示:
<tr><td><input type='text' name='first_name2' /></td><td><input type='text' name='last_name2'</td></tr>
我查看了 .append(),但不确定如何根据我的情况使用它。我希望能够添加无限量的新表格行。我该怎么做?
最佳答案
首先,将您的 HTML 更正为:
<table class="authors-list">
<tr>
<td>author's first name</td><td>author's last name</td>
</tr>
<tr>
<td>
<input type="text" name="first_name" />
</td>
<td>
<input type="text" name="last_name" />
</td>
</tr>
</table>
<a href="#" title="" class="add-author">Add Author</a>
(我添加缩进只是为了可见性)并且不要使用内联 JavaScript。另外,要保持一致,最好对 HTML 属性使用 "
(双引号),对 JavaScript 字符串使用 '
(单引号)。
其次,做类似的事情:
jQuery(function(){
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
var newRow = jQuery('<tr><td><input type="text" name="first_name' +
counter + '"/></td><td><input type="text" name="last_name' +
counter + '"/></td></tr>');
counter++;
jQuery('table.authors-list').append(newRow);
});
});
它会在表格中添加一行,每次点击具有 add-author
类的链接(只是为了确保没有其他链接受到影响),在名称末尾递增数字每个插入字段的名称加 1。该行将插入到具有 authors-list
类的表的末尾(与链接类的原因相同)。参见 this jsfiddle作为证明。
关于jquery - 如何使用 jQuery 在单击按钮时添加额外的 html 表格行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8018304/