javascript - 数据表:使用剥离的 HTML 进行列搜索
问题描述
引用数据表API。
我实现了单个列搜索并需要对其进行扩展:有一个列显示了一个应用了 HTML 属性/类的按钮。问题:我需要去除 HTML 以便仅搜索按钮的标题。有什么想法我该怎么做?
这是我的代码:
table().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function (e) {
if (e.which == 27) {
$(this).val('');
}
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
解决方案
我相信,您可能需要使用外部(自定义)搜索功能$.fn.DataTable.ext.search
才能仅查找按钮文本(如果这是您想要实现的)。
您可以在下面找到演示:
//Sample source data
const srcData=[
{title:'apple',cat:'fruit',score:'good'},
{title:'strawberry',cat:'berry',score:'good'},
{title:'broccoli',cat:'vegie',score:'bad'},
{title:'durian',cat:'fruit',score:'bad'}
];
//Global variable for button text custom search
var buttonText = '';
//DataTables initialization
const dataTable = $('#mytable').DataTable({
dom: 't',
data: srcData,
columns: [
{title: 'title', data: 'title'},
{title: 'category', data: 'cat'},
//render score property as a button
{title: 'score', data: 'score', render: (data, type, row, meta) => `<button>${data == 'good' ? 'Love it!' : 'Hate it!'}</button>`}
],
});
//Append <tfoot> and searchbars
$('#mytable').append('<tfoot><tr></tr></tfoot>');
dataTable.columns().every(function () {
$('#mytable tfoot tr').append(`<td><input colindex="${this.index()}"></input></td>`);
});
//Custom search function across button text only
$.fn.DataTable.ext.search.push((settings, row, rowIndex, rowData, counter) => $(dataTable.row(rowIndex).node()).find('td:eq(2) button').text().toLowerCase().includes(buttonText) || buttonText == '');
//Listen for 'keyup' in <tfoot> searchbars
$('#mytable').on('keyup', 'tfoot td input', function () {
const colindex = $(this).attr('colindex');
//If it's input in 3-rd column (colindex==2)
//simply assign global variabl and re-draw
//table to apply custom search
if (colindex == 2) buttonText = $(this).val().toLowerCase();
//Otherwise search by corresponding column
else dataTable.column(colindex).search($(this).val());
dataTable.draw();
});
tfoot td {
padding-left: 10px !important
}
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>
推荐阅读
- docker - 如何在 Windows 10 上更新 docker-compose 版本
- c++ - 将 svm 分类器设置为 HOG 检测器
- security - GCP:IP地址限制以使用有限IP地址集中的服务帐户
- c# - 如何将 2 个下拉值组合在一起
- ios - Alamofire:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
- database - 文件系统调整大小后 HSQLDB 损坏
- ssl - HTTPS 站点无法访问 Windows Server IIS
- django - Django - 每次查询后修改字段值
- wordpress - WooCommerce 订阅切换订阅
- java - java StAX解析器:不保留属性的双引号