jQuery 添加 HTML 表格列 [英] jQuery add HTML table column

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

问题描述

我有一个这样的 HTML 表格:

I have a HTML table like this:

<table border="1">
    <tbody>
        <tr>
            <td><a href="#" class="delete">DELETE ROW</a>COL 1</td>
            <td><a href="#" class="delete">DELETE COL</a>COL 2</td>
            <td><a href="#" class="delete">DELETE COL</a>COL 3</td>
            <td><a href="#" class="delete">DELETE COL</a>COL 4</td>
            <td><a href="#" class="delete">DELETE COL</a>COL 5</td>
            <td><a href="#" class="delete">DELETE COL</a>COL 6</td>
        </tr>
        <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>

我需要的是一个函数来添加一个新列,其中包含基于其他列的多个 td.问题是在这个 HTML 表中,在添加新列之前使用 jQuery 删除列,因此该函数需要获取当前列配置并进行相应调整,因为行和列总是被删除或添加.

What I need is a function to add a new column with a number of td's based on other columns. The thing is that in this HTML table, columns are removed with jQuery before new columns are added so the function needs to get the current column config and adapt accordingly because the rows and columns are always being removed or added.

我有用于添加新列的代码,但它没有添加标题:

I have this code for adding a new column but it doesn't add the header:

function addACol() {
    var currentNumberOfTDsInARow = $('.tblModel tr:first td').length;
    newColNum = currentNumberOfTDsInARow;
    var rows = $('.tblModel tbody tr');
    for (var i = 0; i < rows.length; i++) {
        var lastTDClone = $(rows[i]).find('td:last').clone();
        $(rows[i]).find('td:last').after(lastTDClone);
    }
}

推荐答案

更新...

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.

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

或者,如果你也想添加一个header,你可以限制前一行为所有大于0的TR:

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>");

标题只会出现在第一个 TR 上:

And the header would only be on the first TR:

$("#myTable tr:first").append("<td>Delete Column LINK</td>");

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

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