从addEventListener()调用函数

时间:2012-11-28 18:18:57

标签: 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)行;在里面,它不起作用:(

谢谢!

1 个答案:

答案 0 :(得分:0)

这在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);