简体   繁体   English

jQuery更新全局变量

[英]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 除非他不识别ii,并向我抛出错误TypeError:playlist [ii]未定义

I've tried window.ii, same error. 我试过window.ii,同样的错误。

$(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: 尝试像这样声明playlist

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. 您需要将播放列表变量移到onload事件方法之外。

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. 您可能也想将ii变量移到外部,否则您将遇到相同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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