简体   繁体   English

在表格的特定列中插入单元格

[英]Insert cells in specific column in Table

I have a Table with 3 thead. 我有一张桌子,上面放着3个剧集。

I'm trying to insert cells in the second column. 我正在尝试在第二列中插入单元格。

I put the insertCell function as follows: 我将insertCell函数如下:

cell = row.insertCell(2); 

but it doesn't work. 但这不起作用。

This is my code : 这是我的代码:

function add() {
    j++;
    count++;
    var table = document.getElementById('table0');
    var row = table.insertRow(-1);
    cell = row.insertCell(1);
    text = count;
    cell.appendChild(document.createTextNode(text));


}

Here is my JSFiddle code 这是我的JSFiddle 代码

Can anyone help me? 谁能帮我?

The index you pass to row.insertCell(index) must be less than or equal to row.cells.length . 传递给row.insertCell(index)必须小于或等于row.cells.length In your case, since row is a brand new row, row.cells.length is 0 , so you must pass 0 or -1 . 在您的情况下,由于row是全新的行,因此row.cells.length0 ,因此您必须传递0-1

Consider the HTML for your table. 考虑表的HTML。 How would you write the HTML for a row containing a single cell, in the 2nd column? 您如何在第二列中为包含单个单元格的行编写HTML? You can't do it! 你做不到! If there is a cell in the second column, there must also be a cell in the first column. 如果第二列中有一个单元格,则第一列中也必须有一个单元格。

To create a new row in table , with a cell in the second column: 要在table创建新行,并在第二列中包含一个单元格:

var row = table.insertRow(-1);
var firstCell = row.insertCell(-1);
var secondCell = row.insertCell(-1);

To give it the appearance of having no cell in the first column, use CSS to git rid of the border and any other styles that make it look like a cell: 为了使它在第一列中没有任何单元格的外观 ,请使用CSS去除边框和其他使其看起来像单元格的样式:

firstCell.className = "empty";
.empty {
    border: 0 none;
}

http://jsfiddle.net/54pmo8oy/14/ http://jsfiddle.net/54pmo8oy/14/

I'm not clear whether this is what you're trying to do, but hopefully it's close. 我尚不清楚这是否是您要尝试执行的操作,但希望它已经完成。 Clicking the button will add a new cell to the second column with each click: 单击按钮将在每次单击时将新的单元格添加到第二列:

(function () {
    var count = 1,
        add = function () {
            var table = document.getElementById('table0'),
                row = table.rows[0],
                cell = row.insertCell(1),
                text = count;
            cell.innerHTML = text;
            count++;
        };
    document.getElementsByTagName('button')[0].addEventListener('click', function () {
        add();
    });
    add();
}());

JSFiddle JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM