无法使用按钮从动态生成的表中正确删除行 [英] Can't properly delete rows from a dynamically generated table using a button

查看:152
本文介绍了无法使用按钮从动态生成的表中正确删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它应该在表中生成行,其中每行都有自己的内容和删除按钮。

I have the following code which is supposed to generate rows in a table where each row has its own content and delete button.

<!DOCTYPE html>
<html>
    <head>
        <title>table</title>
    </head>
    <body>
        <input id="inputText">
        <button onclick = "addRow()">Add text</button>

        <table id = "table">
        </table>
        <script>
            function addRow(){

                var newRow = document.createElement("tr");
                var col1 = document.createElement("td");
                var col2 = document.createElement("td");
                newRow.appendChild(col1);
                newRow.appendChild(col2);

                var button = document.createElement("button");
                button.innerHTML = "delete";

                button.onclick = function () {
                    var index = this.parentNode.parentNode.rowIndex;
                    document.getElementById("table").deleteRow(index);
                }
                col1.appendChild(button);


                var enteredText = document.getElementById("inputText").value;
                col2.innerHTML = enteredText;

                document.getElementById("table").appendChild(newRow);

            }
        </script>
    </body>
</html>

问题在于无论我按哪个删除按钮,它都会删除最后一行。
我尝试使用 console.log(this.parentNode.parentNode)查看它是否返回正确的< tr> 对象,确实如此。但由于某种原因,无论按下什么按钮,属性 rowIndex 都是-1;因此只删除最后一行。这是否意味着每个动态生成的< tr> 都不知道它的行索引?

The problem is that no matter which delete button I press, it deletes the last row. I tried using console.log(this.parentNode.parentNode) to see if it returns the right <tr> object, and it indeed does. But for some reason, the attribute rowIndex is -1 no matter what button is pressed; hence only the last row is deleted. Does it mean that each dynamically generated <tr> doesn't know its row index?

推荐答案

您可以使用 HTMLTableElement.insertRow() 函数。

You can use HTMLTableElement.insertRow() function instead.

var newRow = document.getElementById("table").insertRow();
// newRow.rowIndex will return you the proper index

这是一个工作小提琴

Here is a working fiddle

更新

这是Webkit布局引擎中的一个错误(也转移到了分叉的Blink引擎)。这就是为什么它在Firefox中运行良好但在早期版本的Chrome (Blink)或Safari(Webkit)中运行良好。

It was a bug in the Webkit layout engine, (that moved to the forked Blink engine as well). This is why it works well in Firefox but not in earlier versions of Chrome (Blink) or Safari (Webkit).

错误报告是此处,现已修复。

The bug report is here, it's fixed now.

这篇关于无法使用按钮从动态生成的表中正确删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆