0

我查看了排序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.

请指出我的错误。谢谢!

4

1 回答 1

2

在最后一个循环中,您只是迭代 Id 并尝试附加 Id,而您应该使用这些 Id 附加 DOM 元素

尝试

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

见工作小提琴

于 2013-08-01T06:35:44.643 回答