The following code works (alert pops up):
var sound = document.getElementById("music");
sound.addEventListener("play", function () {
alert("playing");
});
....
....
<audio controls id="music">
<source src="http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg"/>
</audio>
But why does this not work?
var sound = document.getElementsByClassName("music");
sound.addEventListener("play", function () {
alert("playing");
});
....
....
<audio controls class="music">
<source src="http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg"/>
</audio>
This doesn't work either in case getElementsByClassName returns something different than getElementById:
('.sound').addEventListener("play", function () {
alert("playing");
});
....
....
<audio controls class="music">
<source src="http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg"/>
</audio>
All I changed was instead of an ID, I gave it a class (since I have multiple instances of this audio player), and used getElementsByClassName instead of getElementById. I thought getElementsByClassName was compatible with all browsers now? I'm using latest Firefox.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…