Mik*_*ike 4 javascript arrays html-table
我有这个数组:
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
Run Code Online (Sandbox Code Playgroud)
我想将整个数组作为html表打印出来.我怎么做到这一点?
我试过这个,但只能得到印刷品的最终名称:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>
<script type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
var obj = eval ("(" + txt + ")");
for (i=0; i<txt.length; i++){
document.getElementById("fname").innerHTML=obj.employees[i].firstName
document.getElementById("lname").innerHTML=obj.employees[i].lastName
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
var table = document.createElement("table");
for (var i = 0; i < employees.length; i++) {
var row = table.insertRow(-1);
var firstNameCell = row.insertCell(-1);
firstNameCell.appendChild(document.createTextNode(employees[i].firstName));
var lastNameCell = row.insertCell(-1);
lastNameCell.appendChild(document.createTextNode(employees[i].lastName));
}
document.body.appendChild(table);
Run Code Online (Sandbox Code Playgroud)
使用jQuery,您可以:
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
// $.parseJSON will parse the txt (JSON) and convert it to an
// JavaScript object. After its call, it gets the employees property
// and sets it to the employees variable
var employees = $.parseJSON( txt ).employees;
var $table = $( "<table></table>" );
for ( var i = 0; i < employees.length; i++ ) {
var emp = employees[i];
var $line = $( "<tr></tr>" );
$line.append( $( "<td></td>" ).html( emp.firstName ) );
$line.append( $( "<td></td>" ).html( emp.lastName ) );
$table.append( $line );
}
$table.appendTo( document.body );
// if you want to insert this table in a div with id attribute
// set as "myDiv", you can do this:
$table.appendTo( $( "#myDiv" ) );
Run Code Online (Sandbox Code Playgroud)
jsFiddle:http://jsfiddle.net/davidbuzatto/aDX7E/
| 归档时间: |
|
| 查看次数: |
36030 次 |
| 最近记录: |