【问题标题】:Insert all divs with same class into an array?将所有具有相同类的 div 插入到数组中?
【发布时间】:2012-02-04 10:35:26
【问题描述】:

我想将所有具有 .page 类的 div 插入到数组中,然后使用数组迭代调用每个 div。例如数组 pages[] 应该允许我为 pages[2] 中的 div 添加某些效果。

【问题讨论】:

  • 你有一些示例代码要分享吗?您可以使用 index() - api.jquery.com/index - 或 ':eq' 选择器,而不是将 div 添加到数组中。
  • 为什么不使用 $("div.page:eq(2)") 而不是构建数组?
  • 非常感谢您的提示,派上用场了!

标签: javascript jquery arrays class html


【解决方案1】:
var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
    //apply your effects using pageDivs[i]
}

【讨论】:

    【解决方案2】:

    你想这样做吗?

    <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>
    

    【讨论】:

      【解决方案3】:

      我认为某些浏览器不支持 getElementByClassName。但是您可以像这样使用 calssName 属性:

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

      【讨论】:

        【解决方案4】:

        .getElementsByClassName is not supported

        如果你想要the jQuery way:

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

        愉快的迭代。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-14
          • 2013-05-25
          • 1970-01-01
          • 1970-01-01
          • 2014-07-22
          • 1970-01-01
          • 2014-09-09
          • 1970-01-01
          相关资源
          最近更新 更多