如何在javascript中获取数组的下一个元素
How to get the next element of an array in javascript?
我正在用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);
};
相关文章:
- JavaScript数组包含一个值
- 如何获取 JSON 数组下存在的相应值
- 使用事件更改数组的一个元素
- 从 javascript 数组创建一个 Jquery 数组
- 使用javascript匹配字符串中数组的一个元素
- Angular2从数组创建一个列表
- 在Javascript数组或一个对象中存储多个数据所需的Tweak
- 你能给被劫持的JavaScript数组添加一个函数吗
- 从带有循环的数组中一个接一个地在画布上绘制形状
- 将图像数组从一个窗口传递到另一个窗口,并在javascript的新窗口中显示图像
- 使用拆分字符串的数组创建一个对象
- 多维数组 - 创建一个表
- 使用类似查询的对象过滤器数组下划线
- Javascript使用map从一维数组创建一个二维数组
- 角度范围变量中的数组只有一个成员
- 将数组从一个函数传递到另一个函数
- 将 php 数组发送到 jquery ajax 并从该数组创建一个 each 循环
- 角度.js:如何更新数组的一个项目
- 数组最后一个单元格中不需要的对象
- 挖空可观察数组下拉绑定问题