getElementsByClassName不工作,但为的getElementById [英] getElementsByClassName not working but getElementById is
问题描述
以下code ++工程(警报弹出):
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>
这不工作无论是在案件getElementsByClassName返回不同的东西比的getElementById:
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>
所有我改变了,而不是一个ID,我给它一个类(因为我有这样的音频播放器的多个实例),并用getElementsByClassName代替的getElementById。我以为getElementsByClassName与现在所有的浏览器兼容吗?我使用的是最新的Firefox。
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.
推荐答案
我是pretty确保 document.getElementsByClassName()
将返回元素的集合,即使只有一个与页面上的类名的元素。所以,你不能实际应用中的事件侦听器的音频元素,但元素的数组。
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.
如果总是会有只有一个类的声音元素,尝试 VAR声音= document.getElementsByClassName(音乐)[0];
If there will always be only one element of class sound, try var sound = document.getElementsByClassName("music")[0];
.
这篇关于getElementsByClassName不工作,但为的getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!