Datatables: поиск по столбцам с раздетым HTML - PullRequest
2 голосов
/ 16 апреля 2019

Ссылка на таблицы данных 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();
        }
    });
});

1 Ответ

3 голосов
/ 16 апреля 2019

Полагаю, вам может понадобиться использовать внешнюю (настраиваемую) функцию поиска $.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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...