jQuery&“未定义&"在附加到html元素时打印 [英] jQuery "undefined" prints when appending to html element

查看:83
本文介绍了jQuery&“未定义&"在附加到html元素时打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个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的规则,将undefinedfor循环生成的字符串连接起来,以得到结果.

You did not set an initial value, so it is set to undefined. According to JS rules for concatination, this undefinedis then concatenated with the strings generated by the for loop leading to your result.

这篇关于jQuery&amp;“未定义&amp;"在附加到html元素时打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆