Numbering dynamic table rows

前端 未结 3 957
失恋的感觉
失恋的感觉 2021-01-28 18:50

I\'m working on making a dynamic HTML table using jQuery. In a table, my user has two interactions:

  1. Append a row
  2. Remove a specific row

The

相关标签:
3条回答
  • 2021-01-28 19:29

    After the user has appended a row, or deleted one, you just need to iterate over the "number" cells. If we assume that you have a <td> element, we:

    1) give them a nice ID, e.g. row_0, row_1, etc...

    2) write a function to iterate over them:

    function updateRows(){
        $('[id*="row_"]').each(function(index){
            $(this).html(index + 1); // add +1 to prevent 0 index.
        };
    };
    
    0 讨论(0)
  • 2021-01-28 19:34

    http://jsfiddle.net/mblase75/LNXae/1/

    First, wrap the counter number in a <span> with a class for easy finding later:

    $new_row.children('td').prepend('Row #<span class="num">' + ($new_row.index() + 1) + "</span>");
    

    Then update all these spans with an .each loop after you remove the desired row. The first argument passed into .each's callback function is a zero-based index number, and the second is the HTML element:

        var $row = $(this).closest('tr'),
            $table = $row.closest('table');
        $row.remove();
    
        $table.find('tr').each(function(i, v) {
            $(v).find('span.num').text(i + 1);
        });
    
    0 讨论(0)
  • 2021-01-28 19:40

    I have written a jquery plugin which does exactly this, and you shouldnt need to "number" the rows per-se. All you need to do when deleting a row is to pass the index of the row being deleted.

    eg, if you have a delete button in a row:

    <table>
     <tr>
        <td> <input type="button" class="delete" value="delete this row" /></td>
     </tr>
    </table>
    

    The jQuery might look like

    $('.delete').click(function(){
     var index = $(this).parents('tr').index();
     // tell your plugin to delete row "index"
    });
    

    The method from my plugin which does this looks something like:

    removeRow: function (index) {
            return this.each(function () {
                var $this = $(this);
                var $tbody = $('tbody', $this);
                var $tr = $('tr', $tbody).eq(index);
                $this.trigger('rowRemoved', [$tr]);
                $tr.remove();
            });
        }
    
    0 讨论(0)
提交回复
热议问题