javascript 将所有具有相同类的 div 插入一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9140212/
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
Insert all divs with same class into an array?
提问by Alex G.
I want to insert all divs which have the class .page into an array, then call each using the array iteration. For example the array pages[] should allow me to add certain effect to the div in pages[2].
我想将所有具有 .page 类的 div 插入一个数组,然后使用数组迭代调用每个。例如数组 pages[] 应该允许我向 pages[2] 中的 div 添加某些效果。
采纳答案by Umesh Patil
Do you want to do like this ?
你想这样做吗?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr=[];
$(".page").each(function(){ arr.push($(this));});
$.each(arr,function(key,val){ val.css('color','gray')});
});
</script>
</head>
<body>
<b>.page content will be colored in gray.</b><br/><br/>
<div class="dontDo">The quick </div>
<div class="page">brown fox jumps</div>
<div class="doIt"> over the lazy dog</div>
<div class="page"> over the lazy dog</div>
</body>
</html>
回答by Sunil Kumar B M
var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
//apply your effects using pageDivs[i]
}
回答by Ved
I think in some of browsers getElementByClassName is not supported.However you can use calssName property like this :
我认为在某些浏览器中不支持 getElementByClassName。但是您可以像这样使用 calssName 属性:
function getElementsByClassName( strClassName, obj ) {
if ( obj.className == strClassName ) {
//insert this elm into array
array.push(obj);
}
}
回答by Daniel Szabo
.getElementsByClassName is not supported< IE8. If you aren't worried about that, then Sunil's response will work for you.
不支持.getElementsByClassName < IE8。如果您对此并不担心,那么 Sunil 的回答对您有用。
If you want the jQuery way:
如果你想要jQuery 方式:
$(".page").each(function(index) {
// do stuff here
});
Happy iterating.
快乐迭代。