【问题标题】:jQuery TableSorter Plugin error on init : cannot read property '0' of undefined初始化时的 jQuery TableSorter 插件错误:无法读取未定义的属性“0”
【发布时间】:2012-01-16 10:51:07
【问题描述】:

我想用 jQuery Plugin TableSorter 对我的表进行排序。所以我得到了这张桌子:

<table id="stats" class="zebra-striped">
 <thead>
  <tr>
   <th>Date</th>
   <th>Annonce</th>
   <th>Support</th>
   <th>Nb Assoc.</th>
   <th>Nb Transfo.</th>
   <th>Cout</th>
  </tr>
 </thead>
 <tbody>
 </tbody>
</table>

所以你可以看到我的表是空的,只有标题。所以我用空单元格初始化tablesorter:

$("table#stats").tablesorter({ sortList: [[0,0]]});

我立即收到此错误:

jquery.tablesorter.min.js:4 Uncaught TypeError: Cannot read property '0' of undefined

仅供参考,我的 js 已加载:

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.5.1.min.js">\x3C/script>')</script>
<script src="js/bootstrap-dropdown.js"></script>
<script src="js/bootstrap-scrollspy.js"></script>
<script src="js/jquery.tablesorter.min.js"></script>

知道为什么我会得到这个以及如何使插件再次工作吗?

谢谢

【问题讨论】:

  • 听起来你的tablesorter函数没有正确加载,你能检查一下页面中加载的javascript文件吗?
  • @JoJa:刚刚检查过。似乎还好。我编辑帖子以包含它;)
  • 如果你放了一个空的 里面有空的 ?
  • 根据plugin documentation,我可以用一个空表来初始化它:(
  • 在您包含的文档中,他们首先用数据填充表格,然后调用该 sortList 方法。

标签: jquery jquery-plugins tablesorter


【解决方案1】:

您的表中需要有数据,然后才能对其调用 sortList 方法。这是因为您在此方法中应用了索引,如果没有数据存在,将不会找到任何记录,并且会抛出“无法读取未定义的属性 '0'”错误。

【讨论】:

    【解决方案2】:

    当有空表时不宜使用tablesorter,所以可以使用这个条件:

    if ($("table#stats tbody tr").length > 0)
       $(this).tablesorter({ sortList: [[0,0]]});
    

    【讨论】:

      【解决方案3】:

      不需要在表格中包含数据。以这种方式初始化您的表:

      $("table#stats").tablesorter();
      

      然后,在表格中插入数据后,您必须告诉插件表格已更新并对其进行排序:

      $("table#stats").trigger("update");
      var sorting = [[0,0]];
      $("table#stats").trigger("sorton",[sorting]);
      

      【讨论】:

        【解决方案4】:

        我无法让这些工作,所以我为 tablesorter 的初始化设置了一个超时...

        setTimeout(function() {$('table').tablesorter();}, 10000);
        

        【讨论】:

        • 这是 stackoverflow 中几十个帖子中唯一对我有用的帖子;)谢谢!
        【解决方案5】:

        我注意到在http://tablesorter.com/ 找到的最新版本(我认为是 2.0.5b)会发生这种情况,但在早期版本中并没有发生这种情况(我有一份 2.0.3 的副本,它有效在那里面)。但是,https://github.com/Mottie/tablesorter 有一个 fork 版本,维护得更好,并且没有这个错误。

        【讨论】:

          【解决方案6】:

          我收到一个错误“无法读取未定义的属性‘格式’”。在我的情况下,由于 'tbody' 中的 'td' 数量与 'thead' 中不同的数量而发生错误

          【讨论】:

            猜你喜欢
            相关资源
            最近更新 更多
            热门标签