Django中Ajax更新Table后丢失sortable排序功能求助
问题:Ajax更新表格后sorttable.js排序功能丢失
我用sorttable.js实现HTML表格排序,原本功能正常:
引入脚本:
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
只要给表格加上sortable类就能启用排序:
<table id='myTable' class="table table-striped table-hover table-bordered fixed_header sortable">
但通过Ajax筛选更新表格后,内容更新正确,排序功能却没了。我试过在home.html和Ajax返回的filter.html里都放脚本,也参考过相关问题,还是没解决。
我的Ajax代码
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script> <form id="searchform" method="POST" action="{% url "article-filter" %}"> {% csrf_token %} <input type="text" id="txtSearch" name="txtSearch"> <button type="submit" >Submit</button> </form> <script> $("#searchform").submit(function(e) { e.preventDefault(); $.ajaxSetup({ data: {txtSearch: $('#txtSearch').val(), csrfmiddlewaretoken: '{{ csrf_token }}' },}); $.ajax({ type: "POST", url: "article-filter/", dataType: 'json', }).done(function(data) { $('#myTable').html(data.html_table); }); }); </script>
表格代码(home.html和filter.html)
<table id='myTable' class="table table-striped table-hover table-bordered fixed_header sortable"> <thead class="table-dark"> <tr id='tableHeader'> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Phone</th> <th scope="col">Address</th> <th scope="col">City</th> <th scope="col">State</th> <th scope="col">Zipcode</th> <th scope="col">Created At</th> <th scope="col">ID</th> </tr> </thead> <tbody> {% if records %} {% for record in records %} <tr> <td>{{ record.first_name }} {{ record.last_name }}</td> <td>{{ record.email }}</td> <td>{{ record.phone }}</td> <td>{{ record.address }}</td> <td>{{ record.city }}</td> <td>{{ record.state }}</td> <td>{{ record.zipcode }}</td> <td>{{ record.created_at }}</td> <td><a href="{% url 'record' record.id %}">{{ record.id }}</a></td> </tr> {% endfor %} {% endif %} </tbody> </table>
解决方法
核心原因
sorttable.js在页面首次加载时,会自动扫描并初始化所有带sortable类的表格——给表头绑定点击事件、添加排序相关属性和样式。但你通过Ajax替换表格内部HTML后,原来的这些绑定和属性都被清空了,自然丢失了排序功能。
修复步骤
- 调整脚本引入顺序:先引入jQuery,再引入sorttable.js,避免依赖顺序问题,且不需要重复引入sorttable.js:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
- Ajax回调后重新初始化排序:在表格内容更新完成后,调用sorttable提供的
makeSortable方法,重新对目标表格进行初始化:
修改Ajax的done回调部分:
.done(function(data) { $('#myTable').html(data.html_table); // 重新初始化表格排序 sorttable.makeSortable(document.getElementById('myTable')); });
这样就能在每次Ajax更新表格后,重新激活排序功能了。
内容的提问来源于stack exchange,提问作者Nico44044
相关产品推荐
相关产品推荐

