打印出表格中的Javascript数组 [英] Print out Javascript array in table
本文介绍了打印出表格中的Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];
我想将整个数组打印为 html 表.我将如何做到这一点?
and I would like to print the entire array out as a html table. How would I accomplish this?
我试过了,但只能得到打印的最终名称:
I tried this but could only get the final name the print:
<!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>
推荐答案
使用 jQuery 你可以:
Using jQuery you can do:
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" ) );
jsFiddle:http://jsfiddle.net/davidbuzatto/aDX7E/
这篇关于打印出表格中的Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文