我想做的就是获取表内容并将其放入多维数组的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"
}]


请参阅MDN上的Array.prototype.map()Array.prototype.reduce()

关于javascript - 如何获取表内容并将其作为多维数组放入变量中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25045008/

10-09 15:43