开发者

Applying jQuery function to dynamically added item

开发者 https://www.devze.com 2023-02-06 12:33 出处:网络
My question is basically the same as this one (which never got properly answered). How can I use a jQuery function on an item I add dynamically?

My question is basically the same as this one (which never got properly answered).

How can I use a jQuery function on an item I add dynamically?

Specifically, I want to use the jquery tablesorter plugin on a table that I load on the page dynamically, after the user does somethi开发者_如何学编程ng.

Here's my code:

 results_html += "<table id='results' class='tablesorter><thead>"; 
 [My table contents go here, ommitted for this question]
 results_html += "</tbody></table>";
 $('#book_results').html(results_html);
 $("#results").tablesorter(); 

There are no JS errors on the page, but the tablesorter functions aren't being applied. What can I do?

Thanks!


Tablesorter has a trigger function, which you can call to add a tablesorter to a dynamically added element. See the Ajax example here. Something like this should work for you:

 $("#results").tablesorter(); 
 $("#results").trigger("update");

Sometimes you need to call $("#results").trigger("appendCache");. I haven't found out why yet.


Looking at that code, I can only think of two reasons for that not working:

  1. If results isn't a unique ID on the page.
  2. If the typo in the opening line is actually in your code (you're missing the closing ' after the 'tablesorter' class:

    results_html += "<table id='results' class='tablesorter><thead>"; 
                                                        // ^-- here
    

Fundamentally, it works: http://jsbin.com/ikebu4/2 That doesn't look like much because I haven't included any of the table sorter CSS, but it's functional if you click the column headers. Basically there's a pre-existing table, and then a button to add one dynamically. The tablesorter stuff works for both.

0

精彩评论

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