我使用 Django 和引导数据表来显示我的数据。我基本上可以正常工作,但似乎当我使用 HTMX 进行回调刷新时,所有按钮都会损坏。我认为正在发生的事情是,一个新表格被覆盖在顶部,因为按钮仍然“技术上”工作,但它引用了旧数据。 原始表
如您所见,表格看起来略有不同,底部的搜索状态显示“显示 1 到 1 个条目”。所以它可以工作,但不再像以前那样更新 div 以仅显示适用的结果.
这就是我刷新桌子的方式
<table class='table table-bordered' id="alert-table" hx-get="{% url 'alert_list' %}" hx-trigger="every 15s" hx-swap="innerHTML">
数据表的JS:
<script>
$(document).ready(function () {
var table = $("#alert-table").DataTable({
autoWidth: true,
lengthChange: true,
searching: true,
ordering: false,
columnDefs: [ {
targets: 3,
render: function ( data, type, row ) {
}
} ],
dom: 'lBrtip',
buttons: [
{
// COPY
extend: 'copy',
text: '<i class="bi bi-files"></i>',
className: 'btn btn-secondary',
titleAttr: 'Copy'
},
{
// EXCEL
extend: 'excel',
text: '<i class="bi bi-file-earmark-spreadsheet"></i>',
className: 'btn btn-secondary',
titleAttr: 'Excel'
}
]
})
// // Enable Searchbox at top of page
var newSearch = $('#alert-table').DataTable();
$('#search').keyup(function() {
console.log("test");
newSearch.search($(this).val()).draw();
});
<script>
尝试解决此问题:
//separate the search setup to be callable
function handleSearch() {
// // Enable Searchbox at top of page
var newSearch = $('#alert-table').DataTable();
$('#search').keyup(function() {
console.log("test");
newSearch.search($(this).val()).draw();
});
}
//Call the new function using appropriate handlers for doc load and htmx change.
//first document ready for pageload
$(document).ready(function () {
var table = $("#alert-table").DataTable({
autoWidth: true,
lengthChange: true,
searching: true,
ordering: false,
columnDefs: [ {
targets: 3,
render: function ( data, type, row ) {
}
} ],
dom: 'lBrtip',
buttons: [
{
// COPY
extend: 'copy',
text: '<i class="bi bi-files"></i>',
className: 'btn btn-secondary',
titleAttr: 'Copy'
},
{
// EXCEL
extend: 'excel',
text: '<i class="bi bi-file-earmark-spreadsheet"></i>',
className: 'btn btn-secondary',
titleAttr: 'Excel'
}
]
})
handleSearch()
});
//then use htmx.onload to run when htmx does its thing
htmx.onLoad(function() {
handleSearch()
});
有关让 HTMX 与第 3 方脚本配合使用的更多信息,请尝试他们的docs