覆盖datatables.js搜索行为 [英] Overriding datatables.js search behavior

查看:143
本文介绍了覆盖datatables.js搜索行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有关于此主题的一些问题,但是没有一个关于我的确切情况。

There are already several questions here on SO on this subject, however none is about my exact situation.

我有一个包含2列的数据表,其中一个包含文本输入字段,另一个选择。数据表搜索功能的当前行为是在整个选定的HTML中进行搜索。我想要的行为是仅搜索选定的选项。

I have a datatable with 2 columns, one contains text input field and the other a select. The current behavior of datatables' search functionality is to search in the entire select HTML. The behvior I want is search only the chosen option.

我知道我们可以覆盖/拦截搜索/过滤器事件,即

I'm aware we can override/intercept the search/filter events, ie

$('#mapping-table_filter input', data_table.table().container())
    .off('.DT')
    .on('keyup.DT cut.DT paste.DT input.DT search.DT', function (e) {
       data_table.search(...).draw();
    });

// or 

data_table.on('search.dt', function () {

});

但这自 .search 起无济于事不接受回调。

But this does not help since .search does not accept a callback.

JSFiddle
https ://jsfiddle.net/0oabx2mr/

JSFiddle https://jsfiddle.net/0oabx2mr/

如果您搜索第一,第二或第三中的任何一个,则两行仍然可见。我希望能够搜索第二和第三,并且只获取相关行。

If you search for any of "first", "second" or "third" both rows are still visible. I want to be able to search for "second" and "third" and only get the relevant row.

推荐答案

结构简单更改,您的示例可能看起来像这样:

With slight architecture changes, your example may look like that:

var srcData = [
  ['firstOption', 'secondOption', 'thirdOption'],
  ['firstOption', 'secondOption', 'thirdOption'],
  ['firstOption', 'secondOption', 'thirdOption'],
  ['firstOption', 'secondOption', 'thirdOption']
];

var dataTable = $('#mytable').DataTable({
  sDom: 't',
  data: srcData,
  columns: [{
    title: 'Options',
    render: (data, type, row) => '<select>'+row.reduce((options, option) => options += `<option value="${option}">${option}</option>`,'')+'</select>'
  }]
});

var needle = null;
$.fn.DataTable.ext.search.push(
  (settings, row, index) => $(dataTable.cell(`:eq(${index})`,':eq(0)').node()).find('select').val().match(needle) || !needle
);

$('#search').on('keyup', event => {
  needle = $(event.target).val();
  dataTable.draw();
});

<!doctype html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script 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>
  <input id="search"></input>
  <table id="mytable"></table>
</body>
</html>

这篇关于覆盖datatables.js搜索行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆