javascript - 从addEventListener()调用函数

标签 javascript function audio addeventlistener

我有下一个代码,我无法调用ShowMedalMessage()函数

var totalsounds = 3;
var currentsound = 1;
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'notify.wav');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.addEventListener('ended', function() {
    if (currentsound < totalsounds) {
        this.currentTime = 0;
        this.play();
        currentsound = currentsound + 1;
    }
    ShowMedalMessage(1);
}, false);​

如果对该函数的调用在audioElement.addEventListener之前,则它将正确调用,但如果行ShowMedalMessage(1);在里面,它不起作用:(

谢谢!

最佳答案

这在Chrome和Firefox中对我有用。

Hese是现场example

function showMessage() {
  document.write("Sound played");
}

var totalsounds = 3;
var currentsound = 1;
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.addEventListener('ended', function() {
    if (currentsound < totalsounds) {
        this.currentTime = 0;
        this.play();
        currentsound = currentsound + 1;
    }
    showMessage();
}, false);

document.body.appendChild(audioElement);

关于javascript - 从addEventListener()调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13611812/

相关文章:

javascript - 如何清除 selectize.js 下拉列表

javascript - JQuery 选择器 : get one of multiple class names, 作为字符串

function - Jasper 字符串函数方法未定义错误

从 main() 调用函数

python - 使用子进程从其他python文件打开python文件,权限被拒绝错误

audio - 我如何在嘈杂的环境中识别出独特的声音?

python - 在python中提高组合wav文件的播放速度?

javascript - 如何知道用户是否使用 reactjs 连接到蜂窝网络或 wifi

javascript - 使用 Greasemonkey 更新 onclick 的字符串值

c++ - 如何使用 stringstream 作为 C++ 函数的参数?