【问题标题】:Updating livequery table sorting code to .on将 livequery 表排序代码更新为 .on
【发布时间】:2013-03-07 04:00:55
【问题描述】:

我正在将我的网站更新到 jQuery 1.7,并计划在第 2 阶段更新到最新版本。下面是我现有的实时查询代码,我需要更新到 .on() 以维护表格排序功能。

// EXISTING CODE - Applies table sorting to existing and future tables with class of tablesorter
$("table.tablesorter").livequery(function(){ // need to replace this .livequery code

我可以使用此代码对加载 DOM 时存在的表启用表排序,但它不适用于加载 DOM 后创建的表。

// Only works on existing tables
$('table.tablesorter').tablesorter();

我用 .on 尝试了以下代码,但它不响应第一次点击

// Works on existing tables and tables created later, but it will not respond to initial click event
$(document).on('click', 'table.tablesorter', function(e){  $('table.tablesorter').tablesorter(); });

任何建议将不胜感激。

【问题讨论】:

  • 不幸的是,.on 在设计上没有该功能。最简单的方法是保持 livequery;它几乎是最有效的方式,而不是在进行 dom 更改后直接运行所述代码(推荐,但可能需要更改逻辑)
  • 如果您要离开 livequery,请使用 Mottie's fork of tablesorter,它修复了 Christian Bach 原版中的各种问题,或者使用 dataTables。使用这两个插件,您需要在新制作的表上显式调用它们 - 例如。 $(myNewTable).tablesorter();。 “.live()”的职责是委托事件处理;它无法建立自动“小部件化”规则。
  • 感谢您的回复。升级到 jQuery 1.7 后,我无法继续使用 livequery。但是,关于 Christian Bach 更新的表格排序器与 DataTables,您能推荐其中一个吗?
  • 如果您正在控制页面更新(例如 ajax 加载),那么最好的解决方案是在表格完成后对其进行初始化(如在 ajax 回调函数中)。
  • Mottie - 你能给我一个“在完成后初始化表(如在 ajax 回调函数中)”的例子吗?

标签: jquery tablesorter livequery


【解决方案1】:

如果使用ajax加载表格数据,只需在回调函数中初始化表格即可(或done函数如下图;demo):

$.ajax({
  type: "GET",
  // should return raw html of the table
  url: "mysite.com/table"
}).done(function(data) {
  // add the table
  $(data).appendTo('body');
  // initialize it
  $('table').tablesorter({
    theme : 'blue'
  });
});

这只是众多示例之一。

【讨论】:

  • 感谢 Mottie 提供的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 2015-06-22
相关资源
最近更新 更多