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

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

问题描述

我有以下几项:

I have the following:

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

第二,做这样的事情:

Second, do something like that:

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 (只是为了确保没有其他人链接受到影响),在每个插入字段的名称末尾增加数字n ame加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天全站免登陆