问题
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.
回答1:
I'm pretty sure document.getElementsByClassName()
will return a collection of elements, even if there is only one element with that class name on the page. So you're not actually applying the event listener to the audio element, but an array of elements.
If there will always be only one element of class sound, try var sound = document.getElementsByClassName("music")[0];
.
来源:https://stackoverflow.com/questions/15181670/getelementsbyclassname-not-working-but-getelementbyid-is