Javascript getElementsByClassName onclick 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13667533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementsByClassName onclick issue
提问by Dmitriy Levchenko
I'm using Robert Nyman'sscript to get all elements with same class in document, but it doesn't work with onclick or any other event:
我正在使用Robert Nyman 的脚本来获取文档中具有相同类的所有元素,但它不适用于 onclick 或任何其他事件:
var photo = document.getElementsByClassName("photo_class","img",document.getElementById("photo_wrap"));
photo.onclick = function(){alert("Finaly!");
Maybe you know how to fix it? Thanks!
也许你知道如何修复它?谢谢!
回答by aretias
I guess photo is a array. If that's the case, try that:
我猜 photo 是一个数组。如果是这种情况,请尝试:
var photo = document.getElementsByClassName(
"photo_class","img",document.getElementById("photo_wrap")
);
for (var i=0; i < photo.length; i++) {
photo[i].onclick = function(){
alert("Finaly!");
}
};
回答by YardenST
Try
尝试
photo[0].onclick = function(){alert("Finaly!");};
getElementsByClass returns array
getElementsByClass 返回数组
回答by lostsource
getElementsByClassNametakes one parameter, the class name and returns a node list
getElementsByClassName接受一个参数,即类名并返回一个节点列表
If you want <img> elements within 'photo_wrap' with class name 'photo_class' to take the same event handler you could do something like this
如果您希望类名为 'photo_class' 的 'photo_wrap' 中的 <img> 元素采用相同的事件处理程序,您可以执行以下操作
var container = document.getElementById('photo_wrap');
var elements = container.getElementsByTagName('photo_class');
for(var x = 0; x < elements.length; x++) {
// ignore anything which is not an <img>
if(elements[x].nodeName != "IMG") {
continue;
}
elements[x].addEventListener("click",function(){
// do something when element is clicked
this.style.backgroundColor = 'red'; // change element bgcolor to red
},false);
}
回答by Niet the Dark Absol
Are you trying to do this, by any chance?
你是否想这样做,有机会吗?
var photo = document.querySelector("#photo_wrap img.photo_class");
photo.onclick = function() {alert("Hello!");};
回答by Rups
Using jquery, you can easily target all the elements which have a specific class and assign an onclick event to it as shown below:
使用 jquery,您可以轻松定位所有具有特定类的元素并为其分配一个 onclick 事件,如下所示:
$(".photo_class").click(function(){
alert("Finally!")});
If you want to target a specific element which has an id, then you can use the below call:
如果要定位具有 id 的特定元素,则可以使用以下调用:
$("#photo_element_id").click(function(){
alert("Finally!")});

