简体   繁体   English

删除其他行后,为表行提供新索引

[英]Giving an new index to a table row after deleting other row

My code is a simple form with 3 input fields. 我的代码是一个包含3个输入字段的简单表单。 Once the user fills them all in and presses the button it will add a row to the table with the input data aswell as an index number. 一旦用户将它们全部填入并按下按钮,它将向表中添加一行,其中包含输入数据以及索引号。 Like this: 像这样:

https://imgur.com/g5ToOpF https://imgur.com/g5ToOpF

im trying to give each row in a table an index number that is correct with the amount of rows inserted. 我试图给表中的每一行一个索引号,该索引号与插入的行数一致。 This works but now I want it to update the index number when I remove one of the rows from the table. 这工作但现在我希望它从表中删除其中一行时更新索引号。

The following function is triggered when the customer fills in an input field with the desired index number that they want to delete and then press a button. 当客户用他们想要删除的所需索引号填写输入字段然后按下按钮时,将触发以下功能。

    function removeRow() {
        let tabel = document.getElementById("tabel");
        let rows = tabel.getElementsByTagName("tr");
        let indexNumber = document.getElementById("indexnumber").value;

        Object.entries(rows).forEach(([key]) => {
            if(key === indexNumber) {
                tabel.deleteRow(indexNumber);
            }
        })
    }

This works and deletes the row that the customer whats but it doesn't update the index numbers for the other rows. 这可以工作并删除客户的行,但不会更新其他行的索引号。 So when I delete row 5. My table will look like this. 所以当我删除第5行时。我的表格看起来像这样。

https://imgur.com/Zz3sBSI https://imgur.com/Zz3sBSI

I figure I have to loop through all of the rows and set the index to the correct number again. 我想我必须遍历所有行并再次将索引设置为正确的数字。 Can anyone help me out :) ? 谁能帮我吗 :) ?

For the full code check: 对于完整的代码检查:

https://codepen.io/Botert/pen/bJLLWL https://codepen.io/Botert/pen/bJLLWL

grtz, grtz,

Botert Botert

To answer your question, try adding the following snippet in your removeRow() function: 要回答您的问题,请尝试在removeRow()函数中添加以下代码段:

for (var i=1; i<rows.length; i++) {
  var dataRow = rows[i].children[3];
  dataRow.textContent = i;
}

Fiddle here: https://jsfiddle.net/ufszamv4/ 小提琴: https//jsfiddle.net/ufszamv4/

It's outside of the scope of the question, but consider taking a different approach to the problem. 这超出了问题的范围,但考虑采用不同的方法解决问题。 Try placing your rows in an object that has its properties removed. 尝试将行放在已删除其属性的对象中。 The goal is to simply delete a row without having to update the rest of the data. 目标是简单地删除行而不必更新其余数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM