我想做的是获取表格内容并将其作为多维数组放入 jquery 变量中。这可能吗?谁能给我一个例子谢谢。
最佳答案
假设“表格内容”是指“数据”,您可以嵌套调用jQuery.map()
( fiddle ):
// for each content row, retrieve an array of cell-text values
var data = $.map($("tbody tr"), function (tr) {
return [$.map(tr.cells, function (td) {
return $(td).text();
})];
});
输出:
[
["four", "4", "Female"],
["one", "1", "Male"],
["three", "3", "Female"],
["two", "2", "Male"]
]
... 并且在普通的 javascript ( fiddle ) 中:
var data = [].map.call(document.querySelectorAll("tbody tr"), function (tr) {
return [].map.call(tr.cells, function(td) {
return td.textContent;
});
});
现在,as others have suggested ,您可以(也许应该)考虑一个对象数组(fiddle):
// get the header names so we can use them for our object property names
var names = [].map.call(document.querySelectorAll("thead th"), function (th) {
return th.textContent;
});
// for each content row, retrieve an object-representation of the data
var data = [].map.call(document.querySelectorAll("tbody tr"), function (tr) {
return [].reduce.call(tr.cells, function (p, td, i) {
p[names[i]] = td.textContent;
return p;
}, {});
});
输出:
[{
"Name": "four",
"Age": "4",
"Gender": "Female"
}, {
"Name": "one",
"Age": "1",
"Gender": "Male"
}, {
"Name": "three",
"Age": "3",
"Gender": "Female"
}, {
"Name": "two",
"Age": "2",
"Gender": "Male"
}]
参见 Array.prototype.map()
和 Array.prototype.reduce()
在 MDN 上。
关于javascript - 如何获取表格内容并将其作为多维数组放入变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25045008/