I have a <ul> with number of <li>s each having its click handler being attached on page load. There is a button to sort these <li>s. In my sort functionality I have sorted the array of jQuery elements of <li>s and then appended them into the <ul>. this way the sorting works fine but all the <li> lose their click handlers. How do i preserve them ?
var li_array = $('ul li');
li_array.sort( custom_func );
ul.empty().append( li_array.clone(true, true) );
li_array.sort()should not work asli_arrayis not an array, but a jQuery object (unless you use a plugin). Update: It seems, jQuery does indeed provide a sort method and it is the same built-in function that arrays are using. This surprises me a little as I couldn’t find anything in the document. Does someone has more information about this?Furthermore, there is no need to clone the elements (which implies you don’t have to
emptythe list). If you append existing DOM elements to another element, jQuery takes care to detach it first.This should work (assuming
ulreferences your list):If you attach the same click handler to each
<li>element, you better make use of event delegation, using.delegate():More information about delegate:
Event delegation makes use of the fact, that events are bubbling up the DOM tree. The code above adds a click event listener to the
ulelement. The handler will be triggered for every click event that is raised on descendants of this element. Now, jQuery is smart and it executes the handler only forlielements (elements that match the selector, passed as first argument todelegate.The advantage is that you don’t add event handlers to every
lielement, but just one to their common ancestor.You could also add more
lielements to the list without adding the event listeners to them. The event handler bound toulwould also capture clicks on the newly added elements.