简体   繁体   中英

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

I am making my own music player in javascript and am working on the next song button. I have it set up to where the songs get added to the playlist and their corresponding ID number gets stored in an array. Then I index the array looking for the current ID of the song and then when the user hits next it goes to the next song in the array.

Here is my code:

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

The problem that I am experiencing is that once I hit the next button, it stops playing music all together.

newSong is representing the song object, not the id of the song and your song_play method is actually using the song id. change nextSong function to:

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

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