使用tablesorter对多个表进行排序

我正在使用jQuery tablesorter插件来允许用户对我们网站上的数据表进行排序。 我最近遇到了一个区域,其中使用tablesorter的多个表将显示在同一页面上,我没有遇到任何麻烦,并且tablesorter插件运行良好。 我们有几个用户的请求可以同时对所有表进行排序,这很好,因为这些表都具有相同的结构,只是其中的数据不同。 以下是表1的示例:

ID Name Age
1 Bob 24
1 James 33

表2的示例:

 
ID Name Age
5 PJ 28
1 Sue 39

因此,您可以看到该表类似但显示不同的数据。 问题变成了我如何允许用户同时对所有表进行排序,但是让他们仍然单独对表进行排序,因为他们可能想要这样做。 我们想出了如果他们对页面上的第一个表进行排序我们想要使用该事件作为我们的指示,他们希望对页面上的所有表进行排序,与第一个排序结构相同。 我的主要问题是有人会怎么做? 我认为我找到了最好的工作区域,即tableorter小部件,但似乎无法获得最后一块拼图。

以下是我目前为我的widget和tablesorter注册码所拥有的内容:

 $(function() { $("table:not(:first)").tablesorter(); $.tablesorter.addWidget({ id: "tableForceSort", format: function (table) { if (table.config.sortList.length > 0) { $('table:not(:first)').trigger("sorton", table.config.sortList); } } }); $("table:first").tablesorter({ widgets: ['tableForceSort'] }); }); 

正如您所看到的,我将tablesorter添加到页面中的所有表中,但是为第一个表单独注册,以便我可以向该表添加一个特殊的小部件,以强制对页面上的其余表进行排序。 这一切都有效,当我实际尝试对表进行排序并触发触发事件时,问题就出现了,这会导致页面中断,我似乎无法弄清楚原因。 如果有人有办法解决这个或其他一些如何解决这个问题的想法,请告诉我。

谢谢

尝试使用“sortEnd”事件……我必须添加一个标志来防止递归。 希望我添加了足够的评论,这一切都有意义( 演示 )。

 $('table').tablesorter(); // using a flag that prevents recursion - repeatedly calling this same function, // because it will trigger the "sortEnd" event after sorting the other tables. var recursionFlag = false; // bind to table sort end event on ALL tables $("table").bind("sortEnd",function(e, table) { // ignore if the flag is set if (!recursionFlag) { recursionFlag = true; // find other tables to resort (but not the current one) // the current sort is stored in "table.config.sortList" $('table').not(this).trigger("sorton", [ table.config.sortList ]); // reset recursion flag after 1 second... so you can't sort faster // than that or it won't trigger the other tables // you can adjust this value; it all depends on how much data needs // to be sorted in the tables. Run the tablesorter with "debug:true" // to find out the times needed to sort (but do it in IE as it is // the slowest browser) setTimeout(function(){ recursionFlag = false; }, 1000); } });