0

我有这个代码:

var table = document.getElementById("editTable");
var row = table.insertRow(-1);
var i = row.rowIndex;

var remove = document.createElement("input");
    remove.type = "button";
    remove.value = "Remove";
    remove.onclick = (function() {
        var I = i;
        return function() {
            table.deleteRow(I);
        }
    })();

var td1 = row.insertCell(-1);
td1.appendChild(remove);

我在这里阅读了几篇文章,但我不明白我做错了什么。当我尝试删除我创建的最后一行时,我收到此错误:

IndexSizeError: Index or size is negative or greater than the allowed amount
table.deleteRow(I);

我很确定这是一个关闭问题。我了解 javascript 中匿名函数的范围但不了解语法;

4

3 回答 3

1

我认为您在这里过多地考虑了整个函数/匿名函数/闭包的东西。看起来有点太复杂了。试试这个代码:

var table = document.getElementById("editTable");
var row = table.insertRow(-1);

var remove = document.createElement("input");
//Append input first so you can get it's parent
var td1 = row.insertCell(-1)
             .appendChild(remove);

remove.type = "button";
remove.value = "Remove";

remove.onclick = function () {
    var parent = this.parentNode.parentNode; //get the row node
    table.deleteRow(parent.rowIndex - 1); //Delete the row index behind it.
};

jsFiddle

于 2013-06-14T02:04:52.270 回答
1

科里,我看到你有一个可行的解决方案,但你可能对更接近你最初想法的东西感兴趣。

您的原始代码的问题似乎是i在删除其他行后成为当前行索引的不可靠度量。在闭包中捕获i不是解决方案 - 您只需捕获一个仅在捕获时才保证正确的值。

但是捕获row自身,然后row.rowIndex在需要时获取将是可靠的,因为row.rowIndex给出了当前索引,而不是在将行附加到表时的索引。

remove.onclick = (function(row) {
    return function() {
        table.deleteRow(row.rowIndex);
    };
})(row);
于 2013-06-14T11:54:52.687 回答
0

这是代码工作:

var remove = document.createElement("input");
    remove.type = "button";
    remove.value = "Remove";
    remove.onclick = function () {
        var parent = this.parentNode.parentNode; //get the row node
        table.deleteRow(parent.rowIndex); //Delete the row index behind it.
    };

    var td1 = row.insertCell(-1)
         .appendChild(remove);
于 2013-06-14T03:05:27.707 回答