我有一个表,其中有动态行,所以我不知道有多少行。在行中的 td 中,有一些内容需要在单击按钮时在数组中注册。
我需要使用该内容创建一个数组,但它应该采用以下格式:
array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]
在这里,第 1 行...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
在@Chirag Ravindra 代码中稍作修改
// 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["row" + index] = value;
})
console.log(array); // array will be an array of our objects