如何在Jquery中使用JS var(mp3播放列表)

时间:2015-01-16 13:16:04

标签: javascript jquery

我正在尝试为现有的jplayer创建专辑功能。

这是工作静态代码:

$(document).ready(function(){


            new jPlayerPlaylist({
                jPlayer: "#jquery_jplayer_1",
                cssSelectorAncestor: "#jp_container_1"
            }, [
                {title:"01 - Standing (Still)", mp3:"music/Ongesorteerd/01 - Standing (Still).mp3"},
                {title:"02 - Standing (Motion)", mp3:"music/Ongesorteerd/02 - Standing (Motion).mp3"},  // tracklist here
            ]);

            $("#jplayer_inspector_1").jPlayerInspector({jPlayer:$("#jquery_jplayer_1")});

        });

现在我想通过使用变量来填充播放列表。 我设法创建了一个有效的变量,我可以提醒它是JS并检查是否正确。

我的问题是如何替换静态播放列表whit(JS)变量?

这就是我的尝试:

function player(album, tracklist){

            //alert(album+" ## "+tracklist);

            var array = tracklist.split("+");
            var track_count = array.length;
            var tracks = "";
            var i=0;

            while(i < track_count)
            {
                tracks = tracks+'{title:"'+array[i]+'", mp3:"music/'+album+'/'+array[i]+'.mp3"},';
                i++;
            }


            new jPlayerPlaylist({
                jPlayer: "#jquery_jplayer_1",
                cssSelectorAncestor: "#jp_container_1"
            }, [
                $(tracks)  // this is the variable I'm talking about
            ]);

            $("#jplayer_inspector_1").jPlayerInspector({jPlayer:$("#jquery_jplayer_1")});
        }

我会收到以下错误:

错误:语法错误,无法识别的表达式:{title:&#34; 01 - Standing(Still)&#34;,mp3:&#34; music / Ongesorteerd / 01 - Standing(Still).mp3&#34; },{title:&#34; 02 - Standing(Motion)&#34;,mp3:&#34; music / Ongesorteerd / 02 - Standing(Motion).mp3&#34;},

1 个答案:

答案 0 :(得分:0)

在原始代码中,以下代表javascript数组文字:

[
   {title:"01 - Standing (Still)", mp3:"music/Ongesorteerd/01 - Standing (Still).mp3"},
   {title:"02 - Standing (Motion)", mp3:"music/Ongesorteerd/02 - Standing (Motion).mp3"},  // tracklist here
]

在您的代码中,您正在构建一个字符串,而不是数组文字。试试这样的事情

var tracks = [];
while(i < track_count)
{
   tracks.push({
      title: array[i], 
      mp3: "music/'+album+'/'+array[i]+'.mp3"
   });
   i++;
}

new jPlayerPlaylist({
      jPlayer: "#jquery_jplayer_1",
      cssSelectorAncestor: "#jp_container_1"
}, tracks );