使用jquery对Ul标签内的Li标签进行排序

时间:2014-02-26 09:02:56

标签: javascript jquery

脚本:

 for (var i = 0; i < response.length; i++) {
                var toAppend = "<li onclick='SelectUser(this);'  id='user" + response[i].uid + "'><a href='javascript:void(0)'><img src='" + response[i].pic_square + "'  /><span class='Username'>" + response[i].name + "<span class='" + response[i].online_presence + "'></span></a></li>"
                if (!$("#user" + response[i].uid).length ) {
                    $("#OnlineFriendsList").append(toAppend);
                    if (!IsFirstTimeCall)
                        $("#log").append("user <span style='color:Green'>" + response[i].name + " </span>is ready to chat <br>");
                }
            }

HTML:

 <div id="FrdContainer_div" style="width: 293px; height: 600px; overflow: auto">
                <ul id="OnlineFriendsList">
                </ul>
            </div>

如何使用jquery基于li对附加的response[i].name标记进行排序?

1 个答案:

答案 0 :(得分:1)

我会在创建dom结构之前对响应进行排序

response.sort(function (o1, o2) {
    return o1.name.localeCompare(o2.name)
});

for (var i = 0; i < response.length; i++) {
    var toAppend = "<li onclick='SelectUser(this);'  id='user" + response[i].uid + "'><a href='javascript:void(0)'><img src='" + response[i].pic_square + "'  /><span class='Username'>" + response[i].name + "<span class='" + response[i].online_presence + "'></span></a></li>"
    if (!$("#user" + response[i].uid).length) {
        $("#OnlineFriendsList").append(toAppend);
        if (!IsFirstTimeCall) $("#log").append("user <span style='color:Green'>" + response[i].name + " </span>is ready to chat <br>");
    }
}