Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

audio - getElementsByClassName not working but getElementById is

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...