jQuery无限循环w / tablesorter

时间:2010-06-01 18:19:20

标签: javascript jquery

让自己陷入了一个有趣的境地:页面有三张桌子。使用sortEnd,无论何时对一个表进行排序,它都会对其他三个表进行排序。但是,由于我将sortEnd绑定到执行排序的函数,因此您将获得无限循环的排序/求助。它看起来像:

$("table.tablesorter").tablesorter({widgets: ['zebra']}).bind("sortEnd", function() {
    $(this).find("th.headerSortDown,.headerSortUp").each(function(i) {
        index = $(this).attr("cellIndex");
        order = ($(this).is(".headerSortDown")) ? 1 : 0;
        $("table.tablesorter").tablesorter({sortList: [[index,order]]});
    });
});

有关如何清理它的任何提示?

根据以下Nick Craver的反馈,以下代码似乎运作良好:

$("table.tablesorter").tablesorter({widgets: ['zebra']}).bind("sortEnd", function() {
    var current = $(this);
    if (current.data("sorting")) {
        current.data("sorting", false);
        return false;
    }
    $(this).find("th.headerSortDown,.headerSortUp").each(function(i) {
        index = $(this).attr("cellIndex");
        order = ($(this).is(".headerSortDown")) ? 1 : 0;
        $("table.tablesorter").not(current).data("sorting", true).trigger("sorton", [[[index,order]]]);
    });
});

1 个答案:

答案 0 :(得分:0)

您可以使用.data()“标记”其他表,告诉他们在当前排序后不要执行此处理程序,如下所示:

$("table.tablesorter").tablesorter({widgets: ['zebra']}).bind("sortEnd", function() {
  if($(this).data("sorting")) {
    $(this).data("sorting", false);
    return;
  }
  var current = this;
  $(this).find("th.headerSortDown,.headerSortUp").each(function(i) {
    index = $(this).attr("cellIndex");
    order = ($(this).is(".headerSortDown")) ? 1 : 0;
    $("table.tablesorter").not(current).data("sorting", true).tablesorter({sortList: [[index,order]]});
  });
});

这会在所有其他表的数据缓存中存储一​​个布尔值(已经过滤掉this一个再次运行,并使用.not()过滤它。当处理程序执行时,它会检查此值是否存在,如果是,则将其切换为下一个排序,但跳过触发其他表再次排序的循环。