简体   繁体   中英

jquery updating global variable

I have this code where I want to play the next song everytime I click on forward. Except he doesn't recognize ii, and throw me an error TypeError: playlist[ii] is undefined

I've tried window.ii, same error.

$(document).ready(function(){
ii = 0


var playlist = [
    {
        'name' : "Ida Maria - Oh My God",
        'src' : "01 Oh My God.m4a",
        'codec' : 'mp4'
    },
    {
        'name' : "Miley Cyrus - Wrecking Ball",
        'src' : "06 Wrecking Ball.mp3",
        'codec' : 'mpeg'
    }
]


  $('.forward').click(function(){
    ii++
    audio.unload()
    audio.urls = mp3_folder + playlist[ii].src
    audio.load()
    audio.play()
  })

I'd say will tell you that you should not add stuff like that in your global scope. In your case, you do not need to poulate the global scope at all. Keep the scoping minimum.You also had a lot of lexical issues like missing semicolon at the end of lines and closing brackets but try the following:

$(document).ready(function(){
var ii = 0;


var playlist = [
    {
        'name' : "Ida Maria - Oh My God",
        'src' : "01 Oh My God.m4a",
        'codec' : 'mp4'
    },
    {
        'name' : "Miley Cyrus - Wrecking Ball",
        'src' : "06 Wrecking Ball.mp3",
        'codec' : 'mpeg'
    }
];


  $('.forward').click(function(){
    ii++;
    audio.unload();
    audio.urls = mp3_folder + playlist[ii].src;
    audio.load();
    audio.play();
  });

});

Try declaring the playlist like this:

window.playlist

So you'll have

window.playlist = [
    {
        'name' : "Ida Maria - Oh My God",
        'src' : "01 Oh My God.m4a",
        'codec' : 'mp4'
    },
    {
        'name' : "Miley Cyrus - Wrecking Ball",
        'src' : "06 Wrecking Ball.mp3",
        'codec' : 'mpeg'
    }
]

You need to move your playlist variable outside of your onload event method.

var playlist = [
    {
        'name' : "Ida Maria - Oh My God",
        'src' : "01 Oh My God.m4a",
        'codec' : 'mp4'
    },
    {
        'name' : "Miley Cyrus - Wrecking Ball",
        'src' : "06 Wrecking Ball.mp3",
        'codec' : 'mpeg'
    }
];

var ii = 0;

$(document).ready(function(){
    $('.forward').click(function(){
        ii++;
        audio.unload();
        audio.urls = mp3_folder + playlist[ii].src;
        audio.load();
        audio.play();
    });
});

You will probably want to move the ii variable outside as well or you will have the same issue.

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