我需要使用JSON对象创建一个html。我能够创建表并打印结果。出于某种原因,表格会扩展到容器表之外......
JavaScript的:
$(document).ready(function(){
$('<div/>',{
'id':'tablecontainer'
}).appendTo('#maincontainer');
$('<div/>',{
'id':'tablecontainer-1'
}).appendTo('#maincontainer');
$('#maincontainer').append($('<div id="layout" />')
.append($('<table id="set"/>')
.append('<thead><tr> <th>Name</th><th>Age</th> <th>Sex</th> <th>DOB</th> <th>Date Enrolled </th> <th>Date Informed</th> <th>Email Id</th> </tr></thead>')))
var jsonobject = [
{'name':'Bob','age':'20','sex':'male','dob':'2012-12-01','dateenroll':'2012-01-01','dateinform':'2013-01-01','emailid':'bob@gmail.com'},
{'name':'Tom','age':'30','sex':'male','dob':'2012-12-01','dateenroll':'2012-01-01','dateinform':'2013-01-01','emailid':'Tom@gmail.com'},
{'name':'Mike','age':'40','sex':'male','dob':'2012-12-01','dateenroll':'2012-01-01','dateinform':'2013-01-01','emailid':'Mike@gmail.com'},
]
jsonobject.forEach(function(entry) {
$('#set').append();
trObj = $('<tr>');
trObj.append($('<td>').html(entry.name));
trObj.append($('<td>').html(entry.age));
trObj.append($('<td>').html(entry.sex));
trObj.append($('<td>').html(entry.dob));
trObj.append($('<td>').html(entry.dateenroll));
trObj.append($('<td>').html(entry.dateinform));
trObj.append($('<td>').html(entry.emailid));
$('#set').append(trObj);
/*$('#test').append('<b>' + entry.name + '</b>')*/
});
});
的CSS:
#maincontainer{
background-color: black;
width:500px;
height:200px;
color: red;
}
#tablecontainer{
background-color:green;
width:500px;
height:200px;
}
#tablecontainer-1{
background-color:red;
width:500px;
height:200px;
}
#layout{
background-color:light-blue;
width:500px;
height:200px;
}
答案 0 :(得分:2)
快速查看输出
<div maincontainer> <-- height 200px
<div tablecontainer></div> <-- height 200px
<div tablecontainer-1></div> <-- height 200px
<div layout> <-- height 200px
<table set>
</div>
</div>
200 + 200 + 200> 200
答案 1 :(得分:0)
您错过了 </tr>
jsonobject.forEach(function(entry) {
标记
我犯了这个错误。您无需关闭,因为您直接创建了jquery对象
请改为尝试:
此外,您的<table>
结构已<thead>
,之后您将追加<tr>
个节点。您应该在表格中创建<tbody>
,并在<tr>
代码中添加<tbody>
个节点