我正在尝试将我的JSON内容显示到div类" network-info"中。我相信首先写的是然后被数组中的下一个覆盖。我可以用什么来规避这一切并展示一切?
$(function() {
var netinfo = function(data) {
for (var i = 0; i < data.length; i++) {
$(".network-info").html(
"<hr>" +
"<p> Adapter Name: " + data[i].name + "</p>" +
"<p> IP Address: " + data[i].ip + "</p>" +
"<p> MAC Address: " + data[i].mac + "</p>" +
"<p> Adapter ID: " + data[i].id + "</p>" +
"<hr>"
)
}
};
$.ajax({
url: "http://127.0.0.1:8080/dashboard?context=netadapters&node=5",
dataType: 'json',
crossDomain: true,
}).done(function(data) {
netinfo(data);
});
});
答案 0 :(得分:1)
不是直接将输出写入HTML,而是构建一个字符串然后注入字符串,如下所示:
var netinfo = function(data) {
var output = "";
for (var i = 0; i < data.length; i++) {
output +=
"<hr>" +
"<p> Adapter Name: " + data[i].name + "</p>" +
"<p> IP Address: " + data[i].ip + "</p>" +
"<p> MAC Address: " + data[i].mac + "</p>" +
"<p> Adapter ID: " + data[i].id + "</p>" +
"<hr>";
}
$(".network-info").html(output);
};
这实际上比附加数据更好,因为它只修改了DOM一次。
答案 1 :(得分:0)
你是对的,在循环的每次迭代中都会覆盖.network-info
元素的内容。
我建议连接字符串,然后在最后设置.html
。这样浏览器就不必每次都解析HTML并更新DOM ......
var netinfo = function(data) {
var htmlResult = "";
for (var i = 0; i < data.length; i++) {
htmlResult +=
"<hr>" +
"<p> Adapter Name: " + data[i].name + "</p>" +
"<p> IP Address: " + data[i].ip + "</p>" +
"<p> MAC Address: " + data[i].mac + "</p>" +
"<p> Adapter ID: " + data[i].id + "</p>" +
"<hr>"
)
}
$(".network-info").html(htmlResult);
};