Jquery提取不同tr中的JSON数据

时间:2013-02-17 23:39:45

标签: jquery json html-table each

我的例子: http://jsfiddle.net/C7jTg/

var data = [{
  "id": "1",
  "libelle": "1",
  "ordre": "1"
}, {
  "id": "2",
  "libelle": "2",
  "ordre": "2"
}, {
  "id": "3",
  "libelle": "3",
  "ordre": "3"
}, {
  "id": "4",
  "libelle": "4",
  "ordre": "4"
}, {
  "id": "5",
  "libelle": "5",
  "ordre": "5"
}, {
  "id": "6",
  "libelle": "6",
  "ordre": "6"
}, {
  "id": "7",
  "libelle": "7",
  "ordre": "7"
}, {
  "id": "8",
  "libelle": "8",
  "ordre": "8"
}, {
  "id": "9",
  "libelle": "9",
  "ordre": "9"
}, {
  "id": "10",
  "libelle": "10",
  "ordre": "10"
}, {
  "id": "11",
  "libelle": "11",
  "ordre": "11"
}, {
  "id": "12",
  "libelle": "12",
  "ordre": "12"
}, {
  "id": "13",
  "libelle": "13",
  "ordre": "13"
}, {
  "id": "14",
  "libelle": "14",
  "ordre": "14"
}, {
  "id": "15",
  "libelle": "15",
  "ordre": "15"
}, {
  "id": "16",
  "libelle": "16",
  "ordre": "16"
}, {
  "id": "17",
  "libelle": "17",
  "ordre": "17"
}, {
  "id": "18",
  "libelle": "18",
  "ordre": "18"
}, {
  "id": "19",
  "libelle": "19",
  "ordre": "19"
}, {
  "id": "20",
  "libelle": "20",
  "ordre": "20"
}, {
  "id": "21",
  "libelle": "21",
  "ordre": "21"
}, {
  "id": "22",
  "libelle": "22",
  "ordre": "22"
}, {
  "id": "23",
  "libelle": "23",
  "ordre": "23"
}, {
  "id": "24",
  "libelle": "24",
  "ordre": "24"
}];

$('.activiteTable').append("<tr><td align='center' colspan='4'>&nbsp;</td></tr>" +
  "<tr>" +
  "<td align='left' colspan='4'><b>Title:</b></td>" +
  "</tr>");
var rowActivities = '';

$.each(data, function(i, obj) {
  if (i % 4 == 0) {
    rowActivities += "<tr>";
  }

  rowActivities += "<td align='left'>" +
    "<input type='checkbox' id='todo" + i + "' value='" + obj.id + "' class='chBox'/> " + obj.libelle +
    "</td>";

  if ((i % 4 == 0) || (i == 23) && i != 0) {
    rowActivities += "</tr>";
  }


});
$('.activiteTable').append($(rowActivities));
<table cellspacing="3" cellpadding="3" align="left" class="activiteTable" style="clear:both"></table>

我在生成html tr时理解每个函数的工作方式有问题。

我想在html表中提取JSON数据,就像这个模型一样:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

17 18 19 20

21 22 23 24

我不知道最佳做法。 我希望你能帮帮我。

2 个答案:

答案 0 :(得分:0)

你所要做的就是改变这一行(我做了相应的编辑)。

if ((i % 4 == 3) || (i == 23) && i !=0) {

您希望在行尾添加</tr>。这是指数为371115等的时候。

答案 1 :(得分:0)

您可以通过以下方式简化此操作:

var rowActivities = "<tr><td align='center' colspan='4'>&nbsp;</td></tr>"
+ "<tr>"
+ "<td align='left' colspan='4'><b>Title:</b></td>"
+ "</tr>"
+ "<tr>";
$.each(data, function (i, obj) {
    if (i > 0 && i % 4 == 0) {
        rowActivities += "</tr><tr>";
    }
    rowActivities += "<td align='left'>" +
        "<input type='checkbox' id='todo" + i + "' value='" + obj.id + "' class='chBox'/> " + obj.libelle +
        "</td>";
});
rowActivities += "</tr>";
$('.activiteTable').append(rowActivities);

这样做只会将您.activeTables追加到rowActivities一次 在将jQuery对象传递给append()方法之前,无需转换{{1}}。

http://jsfiddle.net/petersendidit/C7jTg/1/