【发布时间】:2018-08-22 03:52:16
【问题描述】:
我是 javascript 新手,我正在尝试将有效的 json 字符串转换为表格。这是我的代码:
function printTable(){
var txt = $("#txtInput").val();
var obj;
try {
obj = JSON.parse(txt);
} catch (e) {
alert(e);
}
var str = "<thead><th>name</th> <th>population</th> <th>capital</th> <th>currency</th> </thead>";
var tr;
for (var i = 0; i < obj.length; i++){
var country = obj[i];
str+="<tr><td>";
str+=country.name+"</td>";
str+="<td>"+country.population+"</td>";
str+="<td>"+country.capital+"</td>";
str+="<td>"+country.currency+"</td>";
}
$("#table").append(str);
}
问题是,它没有打印正确的输出。它打印“名称人口资本货币”。 JSON 字符串是:
{ “国家”:[ {“名称”:“法国”,“人口”:“66000000”,“资本”:“巴黎”,“货币”:“欧元”}, {“名称”:“德国”,“人口”:“82620000”,“资本”:“柏林”,“货币”:“欧元”}, {“名称”:“挪威”,“人口”:“5233000”,“资本”:“奥斯陆”,“货币”:“挪威克朗”}, {“名称”:“俄罗斯”,“人口”:“144526000”,“资本”:“莫斯科”,“货币”:“擦”} ] }
如果有任何帮助,我将不胜感激。谢谢。
【问题讨论】:
-
您的代码从不将
</table>附加到字符串。 -
@Pointy 你为什么这么说?
-
@Ele 哦,我猜
("#table")可能是页面上已经为空的表格元素;那好吧。但是,我过去在使用 IE 时遇到问题,将普通的<tr>行添加到没有包装器<tbody>的表中。 -
@Pointy 关于
tbody的好点
标签: javascript html json dom