HTML表格“添加行”或“删除行”按钮列 [英] HTML table "Add Row" or "Remove Row" button column

查看:816
本文介绍了HTML表格“添加行”或“删除行”按钮列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种在html表的另一行下方添加或删除行的方法。我使用的是dom,可以轻松地添加和删除行,但是当我尝试使用一个按钮列来动态添加和删除行时,就会出现问题。

I need a way to add or remove a row below another row in my html table. I'm using the dom, and can add and remove rows easily enough, but the problem comes up when I try to have a button column that adds and removes rows dynamically.

例如:

    |  Item Type  |     Item     |  Add/Remove Item
====================================================
    |   Fruit >   |     Apple    |   [ Add new ]
----------------------------------------------------
    |             |     Mango    |   [ Remove ]
----------------------------------------------------
    |             |     Pear     |   [ Remove ]
----------------------------------------------------

[添加新] [删除] 条目是按钮。单击 [删除] 按钮将删除该行(删除梨或芒果行)。单击 [添加新] 按钮将添加一个新项目(新水果)。

The [Add new] and [Remove] entries in the right column are buttons. Clicking a [Remove] button would delete the row (remove the pear or mango row). Clicking the [Add new] button would add a new Item (a new fruit).

如果我为按钮指定了html并基于onClick添加了新行,我想不出一种方法来跟踪按钮被单击的行从添加新的。我能想到的最好方法是拥有一个跟踪所有项目类型及其所在行的数组,然后将项目的ID或名称从 onClick()<传递给方法/ code>,但这似乎容易出错且混乱。

If I specified the html for the button and added a new row based on an onClick, I can't think of a way to keep track of which row the button clicked from to add the new one. The best way I can think of is to have an array that keeps track of all the item types and what row they are on, then pass the id or name of the item into the method from onClick(), but this seems error-prone and messy.

为了解决这个问题,我愿意考虑使用任何解决方案(jquery插件,javascript代码等)。有人可以指出我实现此目标的最佳方法吗?

To solve this, I'm willing to consider any solution (jquery plugin, javascript code, anything). Can someone point me to the best way to accomplish this?

推荐答案

就像这样吗?我不知道您将在哪里取值'Mango'和'Pear'..
http:// jsfiddle.net/vPatQ/

Like this? I do not know where you are going to take values 'Mango' and 'Pear'.. http://jsfiddle.net/vPatQ/

$('.AddNew').click(function(){
   var row = $(this).closest('tr').clone();
   row.find('input').val('');
   $(this).closest('tr').after(row);
   $('input[type="button"]', row).removeClass('AddNew')
                                 .addClass('RemoveRow').val('Remove item');
});

$('table').on('click', '.RemoveRow', function(){
  $(this).closest('tr').remove();
});

用于html代码

<table>
    <tr><td>Item Type</td><td>Item</td><td>Add/Remove Item</td></tr>
    <tr><td><input type='text' value='Fruit >'></td>
        <td><input type='text' value='Apple'></td>
        <td><input type='button' class='AddNew' value='Add new item'></td></tr>
</table>

这篇关于HTML表格“添加行”或“删除行”按钮列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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