Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...