将全局变量传递给jQuery中的$(document).ready函数

时间:2012-09-09 06:57:25

标签: javascript jquery

我有一个网站,每首歌都有特定的字母数字ID,比如57bfab618de4191在jQuery播放器中,MP3歌曲必须通过链接分配。

jplayer功能是:

     $(document).ready(function (){
   function playAudio(val) {newVal=val}    

        $("#jquery_jplayer_1").jPlayer({
            ready: function (event) {
                $(this).jPlayer("setMedia", {
    mp3:"http://website.com/dlb.php?file="+newVal                       });
            },
            swfPath: "js",
            supplied: "mp3",
            wmode: "window"
        });
    });

我想在列表中为用户播放不同的歌曲,所以我通过按钮onClick传递了一首歌曲ID

  onClick="playAudio(<?php echo "'".$songid. "'"; ?>)"  

歌曲ID是数据库中指定歌曲的iD,如57bfab618de4191

这样我可以传递值,但是我无法将playAudio函数的参数传递给document.ready函数。

2 个答案:

答案 0 :(得分:3)

var val = 'whateveer'

function playAudio(nval) {
    var val = nval;
    $("#jquery_jplayer_1").jPlayer({
        ready: function(event) {
            $(this).jPlayer("setMedia", {
                mp3: "http://website.com/dlb.php?file=" + val
            });
        },
        swfPath: "js",
        supplied: "mp3",
        wmode: "window"
    });
}

不需要$(document).ready


如果您需要更改歌曲:

var val = '12345'; // your first song
$(document).ready(function() {
    $("#jquery_jplayer_1").jPlayer({
        ready: function(event) {
            $(this).jPlayer("setMedia", {
                mp3: "http://website.com/dlb.php?file=" + val
            });
        },
        swfPath: "js",
        supplied: "mp3",
        wmode: "window"
    });
});

function playAudio(nval) {
    var val = nval;
    $("#jquery_jplayer_1").jPlayer({
        "setMedia", {
            mp3: "http://website.com/dlb.php?file=" + val
        }
    });
    // --- OR ---
    $("#jquery_jplayer_1").changeAndPlay("http://website.com/dlb.php?file=" + val);
}

更多信息:

答案 1 :(得分:2)

您需要使用变量范围。

var newVal = 'default_song_to_play_if_any';

function playAudio(val){
    newVal = val;
    $("#jquery_jplayer_1").jPlayer("destroy");
    $("#jquery_jplayer_1").jPlayer({
       ready: function (event) {
          $(this).jPlayer("setMedia", {
             mp3:"http://website.com/dlb.php?file="+newVal
          });
       },
       swfPath: "js",
       supplied: "mp3",
       wmode: "window"
   });
}

//use this ready function only if you want to play a default song on load
$(document).ready(function(){
    playAudio(newVal); 
});
相关问题