javascript - jQuery click action stripped out by sorting function -


i have function, including following code:

$(list).append(item); $(list).html(     $(list).children("li").sort(function (a, b) {       return $(a).val() - $(b).val();     })); $(item).click(this.listclick); 

(basically, creating <ul> <li> array of items, including listclick function fires when of list items clicked, , sorting list according li value).

if strip out sort function script, works fine (as in, list compiled, click-function working perfectly, albeit not in correct order). however, if sort list, strips out click-functionality (i..e. clicking items doesn't perform listclick function).

why being stripped out? doesn't seem matter whether place sort function before or after listclick line added.

that's because using html method replaces html content of element , has nothing sort method. old elements removed , attached event handlers too. should either use event delegation or better use appendto instead of html:

 $(list).children("li").sort(function (a, b) {       return $(a).text() - $(b).text();  }).appendto(list); 

as appendto moves elements, event handlers preserved.

also note li element doesn't have value property .val() method returns undefined value. should use text method getting textcontent of element. , if list jquery object there no need wrap jquery constructor.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -