开发者

Ordering a list of elements without losing the event handler

开发者 https://www.devze.com 2023-03-14 19:05 出处:网络
I have this list : <ul> <li id=\"6\"> list 6: somethings </li> <li id=\"2\"> list 2: somethings

I have this list :

<ul>
    <li id="6">
        list 6: somethings
    </li>

    <li id="2">
        list 2: somethings
    </li>    

    <li id="4">
        list 开发者_StackOverflow4: somethings
    </li>    

    <li id="5">
        list 5: somethings
    </li>        

    <li id="0">
        list 0: somethings
    </li>    
</ul>

and I'd like (with Javascript/jQuery) order these elements by the id (ASC) keeping the event handler for each element.

Is it possible? How can I do it?


You could just assign the ID's into an array and use sort():

var a = [];
$("ul li").attr('id',function(i,e){
    a.push(e);
});
$.each(a.sort(),function(i,e){
    $("#"+e).appendTo('ul');
});

You are never removing them from the list, just moving them around. Click handler stays intact:

http://jsfiddle.net/niklasvh/nVLqR/


This should work fine. Using detach preserves any events associated with the element. You then use a custom sort function to compare the id attributes of each li element.

var ul = $("ul");
var li = ul.children("li");
li.detach().sort(function(a, b) {
   var compA = $(a).prop("id");
   var compB = $(b).prop("id");
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
ul.append(li);

See an example fiddle here. A click event is attached to the li with ID "6". After the list has been reordered, that click event is still handled.


I think to order them you'll had to remove and add them back into the DOM... and therefore you'll certainly lose the event handler. Are you in control of the handler, can you rebind or use live() instead?

The alternative would be to absolutely position the li elements and use the css position properties (top, right, bottom, left) to move them around, this will keep them in the same order in the DOM, but render them in your desired order.t


This example work for me:

var mylist = $('.item').detach().sort(function (a, b) { 
    return $(a).find(selector).html() > $(b).find(selector).html();
});
$("#container").html(mylist);

or if you want to sort with other informations:

var mylist = $('.item').detach().sort(function (a, b) { 
    return $(a).find(selector).attr('data-title')() > $(b).find(selector).attr('data-title');
});
$("#container").html(mylist);
0

精彩评论

暂无评论...
验证码 换一张
取 消