Javascript deleteRow 导致indexSizeError,需要关闭

标签 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 中匿名函数的作用域,但不了解其语法;

最佳答案

我认为你在这里过度思考了整个函数/匿名函数/闭包的内容。看起来有点太复杂了。试试这个代码:

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

关于Javascript deleteRow 导致indexSizeError,需要关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099835/

相关文章:

Groovy 找到 cloure 中的最后一次迭代吗?

ios - 如何通过在一个屏幕中导航用户来阻止用户

javascript - 在 NodeJS 中使用 process.argv 时行为不一致

javascript - 在 Controller 中使用 $scope var 使用 ng-disable 禁用 Angular 按钮

javascript - Highstocks 多个 x 轴或仅删除日期并使用编号

Ruby Pascal 的带内存的三角形生成器

javascript - JavaScript 中匿名函数中的参数变量

javascript - 从 Cypress Fixture 访问环境变量

javascript - 更新或添加值到列表

javascript - 如何调用一个只传递到另一个函数两次的函数?