Javascript deleteRow导致indexSizeError,需要关闭

时间:2013-06-14 01:36:50

标签: javascript closures

我有这段代码:

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中匿名函数的语法;

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

Corey,我发现你有一个有效的解决方案,但你可能会对你原来的想法更感兴趣。

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

然而,诱捕row本身,然后在需要时获取row.rowIndex将是可靠的,因为row.rowIndex提供当前索引,而不是当时的索引该行被附加到表格中。

remove.onclick = (function(row) {
    return function() {
        table.deleteRow(row.rowIndex);
    };
})(row);

答案 2 :(得分: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);