【问题标题】:Javascript 'Element must be a table' <table id="mytable">Javascript '元素必须是表格' <table id="mytable">
【发布时间】:2019-05-12 01:51:47
【问题描述】:

我正在使用这个表格排序器:https://github.com/tristen/tablesort

但是,当我查看此页面时,我无法对列进行排序。 Chrome 开发工具显示Uncaught Error: Element must be a table at new Tablesort (tablesort.js:6) at mytable.html:12

我假设这张桌子:

<table id='mytable'> 

还有这段代码

document.getElementById('mytable')

正在引用相同的“mytable”。我基于“table-id”的假设,如下所示:http://tristen.ca/tablesort/demo

<!DOCTYPE html>
<html>

<head>
 <script src='./src/tablesort.js'></script>
 <script src='./src/sorts/tablesort.number.js'></script>
 <script src='./src/sorts/tablesort.date.js'></script>
 <link href='./demo/style.css' rel='stylesheet'>
 <link href='tablesort.css' rel='stylesheet'>
</head>
<body>
 <script> new Tablesort(document.getElementById('mytable')); </script>
 <table id='mytable' class="sort" border = "1">
 <thead>
 <tr>

  <th>Name</th>
  <th data-sort-method='number'>Age</th>
  <!-- <th>Age</th> -->
 </tr>
 <tr>
  <td>Ramesh Raman</td>
  <td>22</td>
 </tr>
 <tr>
  <td>Shabbir Hussein</td>
  <td>32</td>
 </tr>
 </thead>
 </table>

</body>
</html>

【问题讨论】:

  • 调用document.getElementById('mytable')时,该表还不存在。见Why does jQuery or a DOM method such as getElementById not find the element?
  • 三点建议:1)demo .html 模板全部使用&lt;table id='sort' class='sort'&gt;。也许您可以尝试相同的方法,看看它是否有效? 2) 通过在 Chrome 开发人员工具中设置断点来调试错误,然后按照自己的方式返回解决方案。 ... AND ... 3) 将您的 Javascript 移至文件的 BOTTOM
  • 好吧,老实说,该库中的错误至少表明您没有设置有效元素,例如参数异常,但这里给出的信息当然是准确的 :)跨度>

标签: javascript jquery html webpage tablesort


【解决方案1】:

它不起作用,因为脚本标记在正文之前加载。将代码放在一个window.onload中:

window.onload = function() {
    new Tablesort(document.getElementById('mytable'));
}

您也可以将脚本标签放在正文的底部,因为它将最后加载,因此能够找到表格。

【讨论】:

  • 我已经将
猜你喜欢
  • 1970-01-01
  • 2018-03-21
  • 2020-08-19
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 2017-03-08
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多