我有一张表格,其中有动态行,所以我不知道有多少行。行中的td内,单击按钮时需要在数组中注册一些内容。

我需要创建一个包含该内容的数组,但是应该采用以下格式:

array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]


在这里,row1 ... row5根据行数动态变化。默认情况下,行的值可以是“”,这很好。

提前致谢。

最佳答案

array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]


上面的语法不正确,因此无法使用。您可以做的是创建一个对象数组,然后使用它。

array1 = [{row1:""},{row2:"abc"}];


或者,如果行号AND值很重要,则这可能是一个更好的结构:

array1 = [{rowId:1, value:""}, {rowId:2, value:"abc"}];


编辑:

要从现有的HTML表创建这种结构,您可以查询行并在每一行上进行操作以创建数组。

// Get a reference to the table element
var table = document.getElementById("table1");
// Initialise empty array
var array = [];

// Query for all the tr elements of the table (rows)
table.querySelectorAll('tr').forEach(function(row, index){
    // For each row, extract value from the requried column
    var value = row.children[0].innerText; // Assuming the value to be added is in the first column (td)
    // Insert new object into array for this row
    array.push({rowId:index, value: value});
})

console.log(array); // array will be an array of our objects

09-25 17:38
查看更多