简体   繁体   English

HTML表格“添加行”或“删除行”按钮列

[英]HTML table “Add Row” or “Remove Row” button column

I need a way to add or remove a row below another row in my html table. 我需要一种方法来添加或删除我的html表中另一行下面的行。 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. 我正在使用dom,并且可以轻松地添加和删除行,但是当我尝试使用一个动态添加和删除行的按钮列时,问题出现了。

For example: 例如:

    |  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. 右列中的[Add new][Remove]条目是按钮。 Clicking a [Remove] button would delete the row (remove the pear or mango row). 单击[Remove]按钮将删除该行(删除梨或芒果行)。 Clicking the [Add new] button would add a new Item (a new fruit). 单击[Add new]按钮将添加一个新项目(一个新的水果)。

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. 如果我为按钮指定了html并基于onClick添加了新行,我想不出一种方法来跟踪单击按钮以添加新行的位置。 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. 我能想到的最好的方法是有一个数组跟踪所有项目类型和它们所在的行,然后将项目的id或名称从onClick()传递到方法中,但这似乎容易出错凌乱。

To solve this, I'm willing to consider any solution (jquery plugin, javascript code, anything). 为了解决这个问题,我愿意考虑任何解决方案(jquery插件,javascript代码等等)。 Can someone point me to the best way to accomplish this? 有人能指出我做到这一点的最好方法吗?

Like this? 像这样? I do not know where you are going to take values 'Mango' and 'Pear'.. http://jsfiddle.net/vPatQ/ 我不知道您将在何处取值“ Mango”和“ 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();
});

for html code 对于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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM