为什么我在列表项之前打印未定义。不要在我犯错的地方。请帮帮我。请考虑下面的代码段
public class HTTPChatMessageReceiver {
public HTTPChatMessageReceiver() {
// TODO Auto-generated constructor stub
}
public void handleMessage(ChatMessage message) {
}
}
var playList = [
["Wild Ones", "Flo Rida"],
["Wings", "Birdi"],
["Pure Love", "White Lion"],
["Hold my hands", "Jess Glynn"]
];
var listSongs = "</ol>";
function print(msg)
{
document.write("<p>" + msg + "</p>");
}
function printSongs( songs )
{
for(var i = 0; i < songs.length; i++)
{
listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
}
listSongs += "</ol>";
print(listSongs);
}
var box = document.getElementById("container");
document.onLoad(box.innerHTML = printSongs(playList));
为什么在打印未定义的歌曲列表之前。请帮忙
答案 0 :(得分:1)
打印和打印歌曲实际上并没有返回任何内容,因此它们返回undefined。
更改
document.write(...stuff...);
要
return ...stuff...;
和
print(listSongs);
要
return print(listSongs);
答案 1 :(得分:1)
那是因为printSongs
函数没有返回任何特定值。如果未指定返回值,则函数将返回值undefined
。
当您运行load
事件中的代码(或至少尝试)时,不应使用document.write
。加载页面后,使用document.write
会隐式调用window.open
,以便创建一个新页面来替换当前页面。
从函数中返回HTML代码而不是将其写出来:
var playList = [
["Wild Ones", "Flo Rida"],
["Wings", "Birdi"],
["Pure Love", "White Lion"],
["Hold my hands", "Jess Glynn"]
];
function print(msg) {
return "<p>" + msg + "</p>";
}
function printSongs(songs) {
var listSongs = "<ol>"; // should be starting tag, not an ending tag
for(var i = 0; i < songs.length; i++) {
listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
}
listSongs += "</ol>";
return print(listSongs);
}
// The property is named onload, not onLoad, and it's in the window object
// It's not a function, you assign a function to it
window.onload = function() {
// get the element inside the load event handler
var box = document.getElementById("container");
box.innerHTML = printSongs(playList);
};
<div id="container"></div>
答案 2 :(得分:1)
我认为有些问题:
listSongs
时,您需要将其设置为<ol>
的开始标记,而不是结束标记。所以它应该变成:listSongs = <ol>;
。document.write
函数中的print
。您可能不需要这样做,因为您已经期望将box
元素的innerHTML
设置为由printSongs
返回的任何内容填充。return
中添加printSongs
语句,以便在完成循环后返回所有listSongs
。代码段:
var playList = [
["Wild Ones", "Flo Rida"],
["Wings", "Birdi"],
["Pure Love", "White Lion"],
["Hold my hands", "Jess Glynn"]
];
var listSongs = "<ol>";
function printSongs(songs) {
for (var i = 0; i < songs.length; i++) {
listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
}
listSongs += "</ol>";
return listSongs;
}
var box = document.getElementById("container");
box.innerHTML = printSongs(playList)
<div id="container"></div>
希望这有帮助。
我还应该补充说,在ol
元素中包装p
将无效,因为p
element only allows inline
HTML elements within it and ol
is not。