when I try to dynamically insert cells to a table with an unknown size (in cells) I got an "Index or size was negative, or greater than the allowed value." error :

    function addTableRow(id, at)
    {
        at = typeof at !== 'undefined' ? at : 0; 
        var table=document.getElementById(id);
        var row=table.insertRow(at); 
            var cells = table.rows[0].cells.length;
            for(var i = 0; i < cells; ++i)
            {
                  row.insertCell(i);
                  row.className="success";
              row.innerHTML = "OMG";
            }
    }

and if I put an alert in the 'for' the error happens in the second row, I think I miss something somewhere, any idea ?

有帮助吗?

解决方案

You're overriding the content of the tr when setting some innerHTML to it. This wipes out the first created td, and if there's not existing row.cells[0], you can't create row.cells[1]. This causes the invalid index error.

You can fix your problem by setting the innerHTML of the newly created cell instead:

for (var i = 0; i < cells; ++i) {
    var cell = row.insertCell(i);
    cell.className = "success"; // or row.className?
    cell.innerHTML = "OMG";
}

A live demo at jsFiddle.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top