jQuery add HTML table column

前端 未结 2 1243
栀梦
栀梦 2020-12-04 18:10

I have a HTML table like this:

DEL
相关标签:
2条回答
  • 2020-12-04 18:47

    Not related to your question but you can make your HTML bit more semantic.

    <table border="1">
        <thead>
            <tr>
                <th><a href="#" class="delete">DELETE ROW</a>COL 1</th>
                <th><a href="#" class="delete">DELETE COL</a>COL 2</th>
                <th><a href="#" class="delete">DELETE COL</a>COL 3</th>
                <th><a href="#" class="delete">DELETE COL</a>COL 4</th>
                <th><a href="#" class="delete">DELETE COL</a>COL 5</th>
                <th><a href="#" class="delete">DELETE COL</a>COL 6</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>ROW 1</td>
                <td>ROW 1</td>
                <td>ROW 1</td>
                <td>ROW 1</td>
                <td>ROW 1</td>
                <td>ROW 1</td>
            </tr>
            <tr>
                <td>ROW 2</td>
                <td>ROW 2</td>
                <td>ROW 2</td>
                <td>ROW 2</td>
                <td>ROW 2</td>
                <td>ROW 2</td>
            </tr>
        </tbody>
    </table>
    

    Modified jQuery code may look like:

    var c = $("#myTable thead th").length;
    $("#myTable thead tr").append("<th><a href=''>Delete</a> Col "+(c+1)+"</th>");
    $("#myTable tr:gt(0)").append("<td>Col</td>");
    
    0 讨论(0)
  • 2020-12-04 19:07

    Update...

    var c = $("#myTable tr:first td").length;
    $("#myTable tr:first").append("<td><a href=''>Delete</a> Col "+(c+1)+"</td>");
    $("#myTable tr:gt(0)").append("<td>Col</td>");
    

    If you need to fix the numbering in the titles, you can use the function we worked on in your previous question.

    Original Answer...

    $("#myTable tr").append("<td>New Column</td>");
    

    Or, if you want to add a header too, you can limit the previous line to all TR greater than 0:

    $("#myTable tr:gt(0)").append("<td>New Column</td>");
    

    And the header would only be on the first TR:

    $("#myTable tr:first").append("<td>Delete Column LINK</td>");
    
    0 讨论(0)
提交回复
热议问题