【问题标题】:How to split the jquery array如何拆分jquery数组
【发布时间】:2011-11-27 08:57:11
【问题描述】:

我有一个表,我需要获取每一行的值(在数组中),例如: [{1,'test'}, {2,'another test'}, {3, 'nothing'}],但我唯一能得到的是: ["1 test", "2 another test","3 nothing"]。我需要通过 ajax 将这些值作为 json 对象发送......并创建另一个表 - 因此我需要一个值数组......

var table = $("table");
var rowsAll = table.find("tbody tr");
rowsAll.each(function(i,l) {
    var rows = [];
    $(this).each(function(t,l){
    rows[rows.length] = cells[t]= $(this).text();
    return rows; //returns rows, but I need cells of each row
    }).serialize();//or get()
});

html 是这样的:

<table id="deal">
<thead>
    <tr>
        <th> num </th>
        <th> string </th>
    </tr>
</thead>
<tbody>
    <tr> <td> 1 </td> <td> test </td> </tr>
    <tr> <td> 2 </td> <td> another test </td> </tr>
    <tr> <td> 3 </td> <td> nothing </td> </tr>
</tbody>
</table>

我真的需要帮助......

【问题讨论】:

  • 在 JavaScript 中没有 {1,'test'} 这样的构造 - 你的意思是对象 {1: 'test'} 还是数组 [1, 'test']
  • 对不起..我只知道基础知识......我只知道我在服务器端需要什么 :(jfriend00 已经给了我答案。无论如何谢谢)

标签: javascript jquery arrays html-table


【解决方案1】:

这种形式的数据毫无意义,因为它很难用 javascript 阅读:

[{1,'test'}, {2,'another test'}, {3, 'nothing'}]

我假设你想要的是这样的:

{"1": "test", "2": "another test", "3": "nothing"}

要获得第二种形式,您可以使用以下代码:

var results = {};
$("#deal tbody tr").each(function() {
    var cols = $(this).find("td");
    results[$.trim(cols.eq(0).text())] = $.trim(cols.eq(1).text());
});

此处的工作示例:http://jsfiddle.net/jfriend00/WjgrC/

【讨论】:

  • 完美!您对格式的看法是正确的 - 只是我不知道如何问:) 谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
相关资源
最近更新 更多