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>
谷歌搜索这个问题产生了很多相关问题,但这并没有帮助我.
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的规则,将undefined
与for
循环生成的字符串连接起来,以得到结果.
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屋!