使用jQuery在两个级别上按id排序div

时间:2013-08-01 06:19:23

标签: jquery html sorting dom

我查看了使用jQuery排序,但我需要排序两个级别。

按字母顺序对顶级和子级别进行排序

我的简单HTML结构就是这样:

<div id="contentObjects">
<div id="Blue" class="sort1">
  <div>
    Blue
  </div>

  <div id="Triangle" class="Blue_sort2">
    <h3>Triangle</h3>

    <div>
      internalName: b_triangle
    </div>

    <div>
      displayName: blue Triangle
    </div>

    <div>
      size: 2
    </div>
  </div>

  <div id="Ball" class="Blue_sort2">
    <h3>Ball</h3>

    <div>
      internalName: b_ball
    </div>

    <div>
      displayName: blue Ball
    </div>

    <div>
      size: 5
    </div>
  </div>
</div>

<div id="Red" class="sort1">
  <div>
    Red
  </div>

  <div id="Cube" class="Red_sort2">
    <h3>Cube</h3>

    <div>
      internalName: r_cube
    </div>

    <div>
      displayName: red Cube
    </div>

    <div>
      size: 5
    </div>
  </div>
</div>

文档准备好后执行此JavaScript

function sortAll() {
    var arrayOfClassIds = $.map($(".sort1"), function(n, i){
              return n.id;
            });
    var arrayOfSubClassIds;

    console.log(arrayOfClassIds);
    $.each($('.sort1'), function() {
        var _id = $(this).attr('id');
        var _parent = $(this);
        arrayOfSubClassIds = $.map($("."+_id+"_sort2"), function(n, i){
              return n.id;
            });

            var arrayOfSortedSubClassIds = arrayOfSubClassIds.sort();
            console.log(arrayOfSortedSubClassIds);
            // start sorting the second level

            $.each(arrayOfSortedSubClassIds, function(i, v) {
                console.log("appending "+v+" to "+_parent.attr('id'))
                // get element with id v and append it to the parent
                $(v).appendTo(_parent);
            });
    });
}
在我的控制台上

日志看起来不错:

["Blue", "Red"]
["Ball", "Triangle"]
appending Ball to Blue
appending Triangle to Blue
["Cube"]
appending Cube to Red 

所以我的预期是有

Blue with Ball and Triangle, then Red with Cube.

但实际上结果是

Blue with Triangle and Ball, then Red with Cube.

请指出我的错误。 谢谢!

1 个答案:

答案 0 :(得分:2)

在最后一个循环中,你只是在Id上迭代并试图追加ID而你应该用那些Id的

追加DOM元素

尝试

 $('#' + v).appendTo(_parent);

见工作fiddle