简体   繁体   中英

Call a function from addEventListener()

I have the next code and I can't call ShowMedalMessage() function

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);​

If the call to the function is before to audioElement.addEventListener, it calls properly, but if the line ShowMedalMessage(1); is inside, it doesn't work :(

Thanks!

this worked for me in chrome and in firefox.

Hese is the live 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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