如何在javascript中获取数组的下一个元素

How to get the next element of an array in javascript?

本文关键字:数组 下一个 元素 获取 javascript      更新时间:2023-09-26

我正在用javascript制作自己的音乐播放器,并正在制作下一首歌曲按钮。我已经将其设置为将歌曲添加到播放列表中的位置,并且它们的相应ID号存储在数组中。然后,我索引数组以查找歌曲的当前ID,然后当用户点击下一首歌曲时,它会转到数组中的下一首歌曲。

这是我的代码:

    $(document).ready(function(){
    $("#player").prop("volume",".5");
});
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","playlist.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
    var songlist = new Array();
    var currentSong;
function song_play(song_id){
    var player = document.getElementById("player");
    player.setAttribute("src", "Music/"+song_id+".mp3");
    player.play();
    songlist.push(song_id);
    alert(JSON.stringify(songlist));
    currentSong = song_id;
            var new_id=song_id-1;
            $("#marquee").empty();
            $("#marquee").append("<span style='color:red;'>Now Playing: </span>"+xmlDoc.getElementsByTagName("artist")[new_id].childNodes[0].nodeValue+"-");
            $("#marquee").append(xmlDoc.getElementsByTagName("track")[new_id].childNodes[0].nodeValue);
};
function add_song(song_id,new_id){
    var artist = xmlDoc.getElementsByTagName("artist")[new_id].childNodes[0].nodeValue;
    var track = xmlDoc.getElementsByTagName("track")[new_id].childNodes[0].nodeValue;
    $("#song_list").append("<a id="+song_id+" href='javascript:void(0)' onclick='song_play(this.id);' class='song'>"+artist+"-"+track+"</a><br/>");
};
function nextSong(currentSong){
        var currentSongIndex = songlist.indexOf(currentSong);
        var newSong = songlist[currentSongIndex + 1];
        song_play(newSong);
};

遇到的问题是,一旦我点击下一个按钮,它就会停止播放音乐。

newSong

表示歌曲对象,而不是歌曲的id,而您的song_play方法实际上使用的是歌曲ID。 将 nextSong 函数更改为:

function nextSong(currentSong){
    var currentSongIndex = songlist.indexOf(currentSong);
    song_play(currentSongIndex + 1);
};