Javascript 未使用 = 运算符执行函数
Javascript not executing functions using = operator
我是 javascript 的新手,所以这是一个基本问题。我创建了一个简单的 mp3 播放器,它加载第一首歌曲,然后播放接下来的几首歌曲。我修改了我在堆栈上找到的这段代码,它有效:
audioPlayer.onended = function() {
if(currentSong < nextSong.length-1) {
audioPlayer.src = nextSong[++currentSong];
document.getElementById('songTitle').innerHTML
= songTitle[currentSong];
}
}
但是,如果我尝试将实现放在它自己的函数中并以这种方式调用函数,它就不起作用:
audioPlayer.onended = nextSong();
function nextSong() {
if(currentSong < nextSong.length-1) {
audioPlayer.src = nextSong[++currentSong];
document.getElementById('songTitle').innerHTML
= songTitle[currentSong];
}
}
我不想每次要使用函数 nextSong() 时都重写代码。我尝试从标签内的按钮调用 nextSong() 函数,例如 this post,但无法调用该函数。感谢您的帮助。
这是一个常见的混淆。你的第二个例子实际做的是 运行 nextSong
函数并将其 return 值分配给 onended
.
相反,您可以将代码更改为:
function nextSong() {
if(currentSong < nextSong.length-1) {
audioPlayer.src = nextSong[++currentSong];
document.getElementById('songTitle').innerHTML
= songTitle[currentSong];
}
}
// Assign the function (nextSong) not its return value (nextSong())
audioPlayer.onended = nextSong;
我是 javascript 的新手,所以这是一个基本问题。我创建了一个简单的 mp3 播放器,它加载第一首歌曲,然后播放接下来的几首歌曲。我修改了我在堆栈上找到的这段代码,它有效:
audioPlayer.onended = function() {
if(currentSong < nextSong.length-1) {
audioPlayer.src = nextSong[++currentSong];
document.getElementById('songTitle').innerHTML
= songTitle[currentSong];
}
}
但是,如果我尝试将实现放在它自己的函数中并以这种方式调用函数,它就不起作用:
audioPlayer.onended = nextSong();
function nextSong() {
if(currentSong < nextSong.length-1) {
audioPlayer.src = nextSong[++currentSong];
document.getElementById('songTitle').innerHTML
= songTitle[currentSong];
}
}
我不想每次要使用函数 nextSong() 时都重写代码。我尝试从标签内的按钮调用 nextSong() 函数,例如 this post,但无法调用该函数。感谢您的帮助。
这是一个常见的混淆。你的第二个例子实际做的是 运行 nextSong
函数并将其 return 值分配给 onended
.
相反,您可以将代码更改为:
function nextSong() {
if(currentSong < nextSong.length-1) {
audioPlayer.src = nextSong[++currentSong];
document.getElementById('songTitle').innerHTML
= songTitle[currentSong];
}
}
// Assign the function (nextSong) not its return value (nextSong())
audioPlayer.onended = nextSong;