我有一个简单的程序,可以将学生对象存储在一个数组中,然后将学生信息打印到网页上。我的程序中有一个print方法,它接受一个参数并访问div元素,然后将内部html元素设置为传递给打印消息的参数。请考虑代码片段以查看document.write方法的工作正常但不是print方法。
var student;
var message = "";
var students =
[
{
name: "Alice",
track: "IOS",
achievements: "Bronze",
points: 20400
},
{
name: "Linda",
track: "Front End Development",
achievements: "Silver",
points: 26000
}
];
function print( msg )
{
var output = document.getElementById("output");
output.innerHTML = msg;
}
for( var i = 0; i < students.length; i++)
{
student = students[i];
message = "<h2> Student : " + student.name + "</h2>";
message += "<p> Track : " + student.track + "</p>";
message += "<p> Achievements : " + student.achievements + "</p>";
message += "<p> points : " + student.points + "</p>";
// print(message);
document.write(message);
}
<div id="output">
</div>
答案 0 :(得分:2)
这是因为您的打印方法取代了整个output div
。因此,循环的每次迭代都会覆盖先前的输出。
您可以更改:
output.innerHTML = msg;
于:
output.innerHTML += msg;
它会正常工作。
答案 1 :(得分:1)
它工作得很好你只需要尊重div中当前的文本。
我在innerHtml调用中添加了+=
以附加新文本
var student;
var message = "";
var students =
[
{
name: "Alice",
track: "IOS",
achievements: "Bronze",
points: 20400
},
{
name: "Linda",
track: "Front End Development",
achievements: "Silver",
points: 26000
}
];
function print( msg )
{
var output = document.getElementById("output");
output.innerHTML += msg;
}
for( var i = 0; i < students.length; i++)
{
student = students[i];
message = "<h2> Student : " + student.name + "</h2>";
message += "<p> Track : " + student.track + "</p>";
message += "<p> Achievements : " + student.achievements + "</p>";
message += "<p> points : " + student.points + "</p>";
print(message);
// document.write(message);
}
&#13;
<div id="output">
</div>
&#13;
答案 2 :(得分:0)
在这种情况下,每次调用时,print
方法都会替换输出的innerHTML
。
因此,如果在循环内调用print
,则唯一显示的结果将是循环中的最后一项。
如果在方法中添加+,您将获得所需的内容。不过,您将需要一种方法来清除div。
var student;
var message = "";
var students = [{
name: "Alice",
track: "IOS",
achievements: "Bronze",
points: 20400
},
{
name: "Linda",
track: "Front End Development",
achievements: "Silver",
points: 26000
}
];
function print(msg) {
var output = document.getElementById("output");
output.innerHTML += msg;
}
for (var i = 0; i < students.length; i++) {
student = students[i];
message = "<h2> Student : " + student.name + "</h2>";
message += "<p> Track : " + student.track + "</p>";
message += "<p> Achievements : " + student.achievements + "</p>";
message += "<p> points : " + student.points + "</p>";
print(message);
}
<div id="output">
</div>