简体   繁体   中英

Javascript onclick variable not working

Can someone tell me why this is not working:

<a href="#" onclick="play('playlist1');">Play Playlist1</a>
function play(id){
    myPlaylist.setPlaylist(id);
}

And this is working:

<a href="#" onclick="play();">Play Playlist1</a>
function play(){
    myPlaylist.setPlaylist(playlist1);
}

There is also a variable called playlist1

var playlist1 = [
    {
        title:"Title",
        artist:"artist",
        mp3: "pathtofile"
    }];

So i need the first one to set the variable to get the right playlist.

It is the same value so it really weird, but i need the first one to work

Can someone help me?

If your first, non-working example, you are passing 'playlist1' as a string, rather than the playlist1 variable. Simply removing the single quotes should be enough to fix it.

Example:

<a href="#" onclick="play(playlist1);">Play Playlist1</a>
function play(id){
    myPlaylist.setPlaylist(id);
}

Another solution would be to look up the variable by the string name via window[id] .

Example:

<a href="#" onclick="play('playlist1');">Play Playlist1</a>
function play(id){
    myPlaylist.setPlaylist(window[id]);
}

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