我正在制作一个JavaScript MP3播放器并遵循在线教程。我自己添加了一些东西,比如可以点击播放它们的MP3文件列表。整个工作正常,直到我手动选择一个MP3文件并且歌曲结束或我点击下一个(或上一个),因为它不会加载下一首歌曲(这确实有用,如果你不手动点击一首歌。)
我收到以下错误:
Uncaught TypeError: Cannot read property 'substr' of undefined
at loadSong (player.js:20)
at next (player.js:76)
at HTMLElement.onclick (VM4443 :88)
我认为它与loadSong(id)中给出的参数有关。代码如下(不需要的代码已被遗漏),提前感谢您的帮助!
var songs = ["Bloed Voor De Kunst.mp3",
"Iemand Moet Het Doen.mp3"];
var songTitle = document.getElementById('songTitle');
var songList = document.getElementById('songList');
var arrayLength = songs.length-1;
var song = new Audio();
var currentSong = 0;
function loadSong(id) {
currentSong = id;
song.src = "mp3/" + songs[currentSong];
var title = songs[currentSong];
var trim = title.substr(0, title.length-4);
songTitle.textContent = trim;
song.volume = volumeSlider.value;
song.play();
setTimeout(showDuration, 1000);
document.getElementById('playpause').setAttribute('onclick','songPlayPause()');
document.getElementById('playpause').setAttribute('class','far fa-pause-circle');
console.log(currentSong);
console.log(arrayLength);
}
function updateSongSlider() {
var c = Math.round(song.currentTime);
songSlider.value = c;
currentTime.textContent = convertTime(c);
if(song.ended) {
next();
}
}
function next() {
var current = currentSong;
if(current !== arrayLength) {
currentSong = currentSong + 1;
}
else {
currentSong = 0;
}
loadSong(currentSong);
}
function getSongList() {
for(var i=0; i < songs.length; i++) {
var title = songs[i];
var trim = title.substr(0, title.length-4);
var playbutton = "<i class='far fa-play-circle' onClick=loadSong('" + i + "')></i>";
document.getElementById('songList').innerHTML += "<li>" + playbutton + "<p>" + trim + "</p></li>";
}
}
答案 0 :(得分:1)
此时,您的数组id
似乎不包含与密钥id
相关的歌曲。所以current !== arrayLength
不是一个好的价值。
在条件为current
的情况下,"1"
的最大值可能是字符1
,它与数字function next() {
var current = currentSong;
if(current !== arrayLength) {
currentSong = currentSong + 1;
}
else {
currentSong = 0;
}
loadSong(currentSong);
}
不完全相同,所以它进入条件并使得加法导致错误的值。
更改:
function next() {
var current = parseInt(currentSong);
if(current < arrayLength) {
currentSong = currentSong + 1;
}
else {
currentSong = 0;
}
loadSong(currentSong);
}
致:
{{1}}