2012-02-04 78 views
1

我想插入所有具有类.page的div到数组中,然后使用数组迭代调用每个div。例如,数组页面[]应该允许我在页面[2]中为div添加特定的效果。将具有相同类的所有div插入到数组中?

+1

您是否有一些示例代码可供分享?您可以使用index() - http://api.jquery.com/index/ - 或“:eq”选择器,而不是将div添加到数组中。 – 2012-02-04 10:40:01

+1

为什么不使用$(“div.page:eq(2)”)而不是构建数组? – 2012-02-04 10:42:06

+0

非常感谢您的提示,派上用场! – 2012-02-04 23:07:59

回答

1

你想这样做吗?

<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> 
4
var pageDivs = document.getElementsByClassName("page"); 
for(i = 0; i < pageDivs.length;i++) 
{ 
    //apply your effects using pageDivs[i] 
} 
0

我觉得在某些浏览器的getElementByClassName不supported.However可以使用calssName属性是这样的:

function getElementsByClassName(strClassName, obj) { 
    if (obj.className == strClassName) { 
     //insert this elm into array 
     array.push(obj); 
    } 
} 
0

.getElementsByClassName is not supported < IE8。如果您不担心这一点,那么Sunil的答复将适用于您。

如果你想the jQuery way

$(".page").each(function(index) { 
    // do stuff here 
}); 

快乐迭代。

相关问题