我有一个div:
<div id="tableContainer">
</div>
我正在用jQuery动态添加一个表:
$(document).ready(function () {
var data = '[{"gameid":"1","gamename":"Halo","gamedescription":"Game about aliens","gamegenre":"FPS"},{"gameid":"2","gamename":"Halo 2","gamedescription":"Game about aliens 2","gamegenre":"FPS"}]';
var json = $.parseJSON(data);
$("#tableContainer").append("<table>");
$("#tableContainer").append("<tr>");
$("#tableContainer").append("<td>Game ID</td>");
$("#tableContainer").append("<td>Game Name</td>");
$("#tableContainer").append("<td>Game Description</td>");
$("#tableContainer").append("<td>Game Genre</td>");
$("#tableContainer").append("</tr>");
$.each(json, function (index, value) {
$("#tableContainer").append("<tr>");
console.log(value.gameid);
$("#tableContainer").append("<td>" + value.gameid + "</td>");
$("#tableContainer").append("<td>" + value.gamename + "</td>");
$("#tableContainer").append("<td>" + value.gamedescription + "</td>");
$("#tableContainer").append("<td>" + value.gamegenre + "</td>");
$("#tableContainer").append("</tr>");
});
$("#tableContainer").append("</table>");
});
我希望将此整个表格水平居中。我正在尝试使用
#tableContainer {
text-align: center;
width: 100%;
}
#table {
margin: 0 auto;
}
但没有成功。有任何想法吗?这是一个小提琴:
http://jsfiddle.net/bn52jk8k/11/
由于
答案 0 :(得分:3)
像这样修改代码
$(document).ready(function () {
var data = '[{"gameid":"1","gamename":"Halo","gamedescription":"Game about aliens","gamegenre":"FPS"},{"gameid":"2","gamename":"Halo 2","gamedescription":"Game about aliens 2","gamegenre":"FPS"}]';
var json = $.parseJSON(data);
var table="<table>"
+ "<tr>"
+ "<td>Game ID</td>"
+ "<td>Game Name</td>"
+ "<td>Game Description</td>"
+ "<td>Game Genre</td>"
+ "</tr>";
$.each(json, function (index, value) {
table+="<tr>"
+ "<td>" + value.gameid + "</td>"
+ "<td>" + value.gamename + "</td>"
+ "<td>" + value.gamedescription + "</td>"
+ "<td>" + value.gamegenre + "</td>"
+ "</tr>";
});
table+="</table>";
$("#tableContainer").append(table);
});
和CSS,
#tableContainer table {
margin: 0 auto;
}
这是小提琴; Jsfiddle Center align