繁体   English   中英

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()都重写代码。 我尝试从标记内的按钮(例如post )调用nextSong()函数,但是无法调用该函数。 谢谢你的帮助。

这是一个普遍的困惑。 第二个示例的实际操作是运行nextSong函数并将其返回值分配给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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM