How can I dynamically add table rows

This question already has an answer here:

  • Add table row in jQuery 31 answers

  • HTML (assuming the thead doesn't change):

    <a href="#" class="button" id="add">Add line</a>
    <a href="#" class="button" id="delete">Delete line</a>
    
    <div style="width:98%; margin:0 auto">
        <table align="center" id="table">
            <thead>
                <tr>
                    <th id="0">Status</th>
                    <th id="1">Campaign Name</th>
                    <th id="2">URL Link</th>
                    <th id="3">Product</th>
                    <th id="4">Dates (Start to End)</th>
                    <th id="5">Total Budget</th>
                    <th id="6">Daily Budget</th>
                    <th id="7">Pricing Model</th>
                    <th id="8">Bid</th>
                    <th id="9">Targeting Info</th>
                    <th id="10">Total Units</th>
                </tr>
            </thead>
            <tbody>
    
            </tbody>
        </table>
    </div>
    

    JavaScript:

    <script type="text/javascript">
    <!--
        var line_count = 0;
        //Count the amount of <th>'s we have
        var header_count = $('#table > thead').children('th').length - 1;
    
        $(document).ready(function() {
            $('#add').click(function() {
                //Create a new <tr> ('line')
                $('#table > tbody').append('<tr></tr>');
    
                //For every <th>, add a <td> ('cell')
                for(var i = 0; i < header_count; i++) {
                    $('#table > tbody > tr:last-child').append('<td id="'+ line_count +'_'+ i +'"></td>');
                }
    
                line_count++; //Keep track of how many lines were added
            });
    
            //Now you still need a function for deleting.
            //You could add a button to every line which deletes its parent <tr>.
        });
    -->
    </script>
    
    链接地址: http://www.djcxy.com/p/22966.html

    上一篇: 如何在单击按钮时复制表格行

    下一篇: 我如何动态添加表格行