0

これは、配列を作成するための許容可能な方法でしょうか

  • 同じクラスを持つ要素、またはより効率的なものがありますか?

    <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);
            })
    
        });
    });
    
  • 4

    2 に答える 2

    0

    関数を使用mapして配列を作成します。

    var newarr = $('li[class~=' + newclass + ']').map(function(){ 
                     return $(this).attr('id');
                  });
    
    于 2013-06-07T21:32:02.687 に答える