如何使用JQuery从这些对象
创建动态表对象是数组类型并存储每个列数据。
我想要这样的表:
+--Start_Hour--Start_Minutes--Start_Month--+
| 11 | 00 | 07 --|
| 03 | 03 | 03 --|
是的,但它的代码不好:(
function GenerateHolidayTable(data) {
var name, number;
var HolidayTableHTML = '';
HolidayTableHTML += '<table class="table"><tr><th>Start_Month</th><th>Start_Day</th><th>Start_Hour</th><th>Start_Min</th><th>End_Month</th><th>End_Day</th><th>End_Hour</th><th>End_Min</th> <th>Description</th></tr>';
$.each(data, function(key, value) {
if (key == "Start_Month") {
HolidayTableHTML += '<tr>';
$.each(value, function(key, value) {
HolidayTableHTML += '<td>' + value + ' </td>';
});
}
..................................
else if (key == "Description") {
$.each(value, function(key, value) {
HolidayTableHTML += '<td>' + value + ' </td>';
});
HolidayTableHTML += '</tr>';
}
});
HolidayTableHTML += '</table>';
$('#HolidayTable').append(HolidayTableHTML);
}
答案 0 :(得分:2)
您可以这样做:
假设所有三个(Start_Month,Start_Hour和Start_Minutes)都具有相同的长度。
var json = "{\"Start_Month\": {\"1\" :\"1\",\"2\" :\"2\",\"3\" :\"3\"},\"Start_Minutes\": {\"1\" :\"10\",\"2\" :\"20\",\"3\" :\"30\"},\"Start_Hour\": {\"1\" :\"01\",\"2\" :\"02\",\"3\" :\"03\"}}";
var jsonObj = JSON.parse(json);
$.each(jsonObj.Start_Hour, function(idx, val) {
var row = "<tr>";
row += "<td>" + val + "</td>";
row += "<td>" + jsonObj.Start_Minutes[idx] + "</td>";
row += "<td>" + jsonObj.Start_Month[idx] + "</td>";
row += "</tr>";
$("#data").append(row);
});
&#13;
table {
width: 100%;
}
table,
td,
th {
border: 2px lightblue solid;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Start_Hour</th>
<th>Start_Minutes</th>
<th>Start_Month</th>
</tr>
</thead>
<tbody id="data"></tbody>
</table>
&#13;
答案 1 :(得分:-2)
您是否查看过Mustache JS等javascript模板系统?
因为它会使这样的事情变得相对容易。