【问题标题】:Create array of elements with same class创建具有相同类的元素数组
【发布时间】:2013-06-07 21:28:56
【问题描述】:

这是一种可接受的创建数组的方法吗?

  • 元素具有相同的类,还是有更有效的方法?
    <ul>
      <li  class="show" id="all">All Posts</li>
      <li  class="show" id="user" data-user="7">My Posts</li>
      <li  class="show" id="follow">Following</li>
    </ul>
    
    $(document).ready(function() {
      var newarr=[];
      $("li").click(function(event) {
        var name = event.target.className;
        var newclass = 'choice';
    
      $(this).addClass(newclass);
      $(this).siblings().removeClass(newclass);
    
      $('li[class~=' + newclass + ']').each(function(index) {
        var thisid = $(this).attr('id');
        newarr[index] = thisid;
        })
    
      $.each(newarr,function(index,value) {
        //console.log(index + value);
            })
    
        });
    });
    
  • 【问题讨论】:

      标签: arrays html-lists each


      【解决方案1】:

      我会使用map 函数来创建数组:

      var newarr = $('li[class~=' + newclass + ']').map(function(){ 
                       return $(this).attr('id');
                    });
      

      【讨论】:

        【解决方案2】:

        我猜newarr[index] = thisid; 应该只是newarr[] = thisid;

        但话说回来,我什至不认为我明白你想做什么。

        您为什么使用 .click 处理程序工作?

        在每次单击时,您将 newclass 设置为单击的项目并将其添加到数组中。但是您也从兄弟姐妹中删除了 newclass,因此先前单击的项目将再次丢失 newclass...所以在 newarr 中,只有最后一个单击的项目将具有 newclass

        【讨论】:

        • 我省略了显示我有几个
            的代码,用户可以从中进行选择,因此数组中可能有多个值。这是否会影响您对我为什么要使用点击处理程序工作的问题?
        猜你喜欢
        • 2023-04-07
        • 2014-06-13
        • 2012-01-23
        • 2017-08-24
        • 1970-01-01
        • 2022-07-07
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多