简体   繁体   中英

Pass a global variable to the $(document).ready function in jQuery

I have a site that has particular alphanumeric ID for every song, say like 57bfab618de4191 In the jQuery player the MP3 song has to be assigned via link.

The jplayer function is this:

     $(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"
        });
    });

I want to play different song present in the list for user so I passed a ID of song via button onClick like this

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

Where song ID is the iD of the song specified in database, like 57bfab618de4191

This way I can pass the value, but I am not able to transfer the parameter of playAudio function to the document.ready function.

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"
    });
}

no need for $(document).ready


if you need to change songs:

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);
}

More info:

You need to play with variable scoping.

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); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM