jQuery“未定义”附加到html元素时打印 [英] jQuery "undefined" prints when appending to html element
问题描述
我正在制作一款jQuery MP3播放器。首先生成歌曲结构(包括关于歌曲的信息),然后使用jQuery将结构添加到div中,如下所示:
I'm making a jQuery MP3 player. The song structure is first generated (including the information about the song), and then the structure is appended to a div using jQuery like this:
function loadFromPlaylist(playlist) {
var songsStructure;
for (var i=0; i<playlist.length; i++) {
songsStructure +=
"<div id='song" + i + "'>" +
"<span class='mpPlaylistArtist'>" + playlist[i].artist + "</span>" +
"<span class='mpPlaylistSong'>" + playlist[i].song + "</span>" +
"<span class='mpPlaylistAlbum'>" + playlist[i].album + "</span>" +
"</div>";
}
$('#mpTracks').append(songsStructure);
}
除了一件事情之外,这完美运作。当这些项目显示在浏览器中时,会在歌曲上方打印一个字符串(undefined),如下所示:
This works perfectly except for one thing. When the items are displayed in the browser, a string ("undefined") is printed above the songs, like so:
<div id="mpTracks">
"undefined"
<div id="song0">...</div>
<div id="song1">...</div>
</div>
使用Google搜索遇到了很多相关的问题,但这并没有帮助我。
Googling this problem yielded alot of related problems but that didn't help me.
有人知道问题可能出在哪里吗?
Does anyone know what the problem might be?
推荐答案
初始化您的变量为空字符串,在使用它之前:
Initialize your variable to an empty string, before using it:
var songsStructure = '';
您没有设置初始值,因此它被设置为 undefined
。根据JS的concatination规则,这个 undefined
然后与由为
循环产生的字符串连接起来,从而得到结果。
You did not set an initial value, so it is set to undefined
. According to JS rules for concatination, this undefined
is then concatenated with the strings generated by the for
loop leading to your result.
这篇关于jQuery“未定义”附加到html元素时打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!