如何在使用 jQuery 单击按钮时添加额外的 html 表格行? [英] How do I add an extra html table row upon button click using jQuery?

查看:18
本文介绍了如何在使用 jQuery 单击按钮时添加额外的 html 表格行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

<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>

每次我点击链接标签以添加作者"时,我都想创建一个如下所示的额外表格行:

and each time I click the link tag to 'add author', I want to create an extra table row like the following:

  <tr><td><input type='text' name='first_name2' /></td><td><input type='text' name='last_name2'</td></tr>

我查看了 .append() ,但不确定如何在我的情况下使用它.我希望能够添加无限数量的新表格行.我该怎么做?

I looked at .append() and I'm not sure exactly how to use it for my situation. And I'd like to be able to add infinite amount of new table rows. How do I do this?

推荐答案

首先,将您的 HTML 更正为:

Firstly, correct your HTML as:

<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 字符串使用 '(单引号).

(I have added indents only for visibility) and do not use inline JavaScript. Plus, be consistent, preferably use " (double quotes) for HTML attributes, ' (single quotes) for JavaScript strings.

其次,做这样的事情:

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 的表的末尾(与链接类的原因相同).请参阅此 jsfiddle 作为证明.

It will add a row to the table with each click on the link having class add-author (just to be sure no other link is influented), incrementing number at the end of the name of every inserted field's name by 1. The row will be inserted at the end of the table having class authors-list (same reason as with class for a link). See this jsfiddle as a proof.

这篇关于如何在使用 jQuery 单击按钮时添加额外的 html 表格行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆