用javascript在表上显示一个空列

Showing an empty column on table with javascript

本文关键字:一个 javascript 显示      更新时间:2023-09-26

我想通过JavaScript在表上添加一个新列。

现在,我想显示在添加索引位置的空列。此外,当在其索引位置添加列时,它必须隐藏。

方法代码:

function addColumn(tblId, colIndexVal)
  {
//New Header 
    var tblHeadObj = document.getElementById(tblId).tHead;
for (var h=0; h<tblHeadObj.rows.length; h++) {
      var newTH = document.createElement('th');
   tblHeadObj.rows[h].insertBefore(newTH, tblHeadObj.rows[h].children[colIndexVal] );
       newTH.innerHTML = "New Col Header";
    }
//New Column cells
    var tblBodyObj = document.getElementById(tblId).tBodies[0];
    for (var i=0; i<tblBodyObj.rows.length; i++) {
      var newCell = tblBodyObj.rows[i].insertCell(colIndexVal);
      newCell.innerHTML = 'new cells'
  )
    }

  }

有谁能建议怎么做吗?由于

这是我的纯javascript 最佳猜测在我认为你想要的,考虑到缺乏清晰度,或我的理解,你的问题。它还提供了两个简单的(未进行安全性检查的)方法,以便更容易地遍历/检索(再次说明:没有进行安全性检查,因此要小心使用或改进它们):

/* trying to reduce the necessity of
   'this.parentNode.parentNode' etc, to
   remove the need to know the exact structure */
Object.prototype.closest = function (elType) {
    var parent = this.parentNode;
    return parent.tagName.toLowerCase() == elType.toLowerCase() ? parent : parent.closest(elType);
};
/* a simple non-sanity-checked means to find,
   and filter, the sibling elements of a node */
Object.prototype.siblings = function (filter) {
    var parent = this.parentNode,
        s = parent.children,
        rs = [],
        c, t;
    for (var i = 0, len = s.length; i < len; i++) {
        c = s[i].className;
        t = s[i].tagName.toLowerCase();
        if (c.indexOf(filter) > -1 || t == filter) {
            rs.push(s[i]);
        }
    }
    return filter ? rs : s;
}
// no attempt whatsoever is being made to make this IE compatible
var table = document.querySelector('table');
function addColumn(e) {
    var self = e.target,
        cell = self.parentNode,
        rows = self.closest('tr').siblings('tr'),
        index = cell.cellIndex,
        newEl;
    for (var i = 0, len = rows.length; i < len; i++) {
        rows[i].insertCell(index + 1);
        newEl = rows[i].children[index + 1];
        // uncomment below if you want to hide:
        // newEl.style.display = 'none';
    }
}
table.addEventListener('click', addColumn, false);

JS提琴演示

关于jsFiddle的例子

您可以通过在每一行插入一个td元素来在表上添加一个新列。

function addCol()
{
    $("table thead tr").each(function() {
        var td = $("<th>");
        var index = $(this).find("th").length;
        td.html("Col index " + index);
        td.appendTo(this);
    });
    $("table tbody tr").each(function() {
        var td = $("<td>");
        td.appendTo(this);
    });
}
addCol();
addCol();

您基本上希望使用eq来获取索引,然后在新创建的索引之前插入新行(可能还有标头)。

像这样:

var table = $("table") // select your table,
    index = 3, // index where to insert
    newRow = $("<td></td>");
table.find("th").eq(index).before(newRow) 

完整示例(添加头部值):http://jsfiddle.net/cTNqX/