【发布时间】:2017-10-02 07:35:26
【问题描述】:
大家好,我正在尝试使用以下代码在表格单元格(一行 3 个单元格)中显示一些 div,但我不断收到包含缺失数据的不正确表格。谁能告诉我如何解决这个问题并每行显示 3 个 div。谢谢
带有示例数据的完整代码:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function myFunction()
{
alert("inside function");
var response= "[\r\n {\r\n \"ID\": \"1\",\r\n \"Title\": \"title 1 \",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/1/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"2\",\r\n \"Title\": \"title 2\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/2/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"3\",\r\n \"Title\": \"title 3\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/3/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"4\",\r\n \"Title\": \"title 4\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/4/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"5\",\r\n \"Title\": \"title 5\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/5/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"6\",\r\n \"Title\": \"title 6\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/6/102.jpg\",\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"7\",\r\n \"Title\": \"title 7\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/7/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"8\",\r\n \"Title\": \"title 8\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/8/102.jpg\",\r\n \"Note\": null\r\n },\r\n {\r\n \"ID\": \"9\",\r\n \"Title\": \"title 9\",\r\n \"Text\": \"\",\r\n \"ImageUrl\": \"http://awebsite/imagges/9/102.jpg\",\r\n \"Note\": null\r\n }\r\n]";
var json = $.parseJSON(response);
var html='';
var x=0; // x is number of cells per row maximum 2 cells per row
for(i in json)
{
// create HTML code
var div = "<div class=\"image\">\n" +
"<a href=\"javascript:doIt('" + json[i].ID + "')\">\n" +
"<img src=\""+ json[i].ImageUrl +"\" alt=\"\" />"+ json[i].Title +"\n" +
"</a>\n" +
"</div>\n";
if(x<3)
{
//alert("1 value of x is:"+x);
html += '<td>'+div+'</td>\n';
//$('#demo > tbody').append(html );
x=x+1;
}else
{
//go to next row and print </tr><tr>
//alert("2 value of x is:"+x);
html += '</tr>\n\n<tr>\n';
$('#demo > tbody').append(html);
x=0;
};
$('#demo > tbody').append(html);
};
};
</script>
</head>
<body onload="myFunction()">
<div class="scroller">
Incorrect :<br>
<table id="demo" cellspacing="0" border="1" style="display: visible;">
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
【问题讨论】:
标签: javascript jquery for-loop html-table