数据表或搜索

Datatables OR search?

本文关键字:搜索 数据表      更新时间:2023-12-31

我使用的是DataTablesjQuery插件。

如果一个术语显示在两个特定列中的至少一列中,我想搜索该表。

下面的当前代码只查找单词"word"位于两个列中的行。我需要找到单词在中的行,或者列中的行。

$table.DataTable().columns([0,1]).search("word");

我考虑过使用全局搜索并将其他列的可搜索选项设置为false,但我找不到在运行时更改此选项的方法。

搜索所有列

搜索表时可以使用正则表达式。

例如,下面的代码显示在所有列中包含单词AngelicaLondon的搜索结果。

var table = $('#example').DataTable();
table
    .search('Angelica|London', true, false)
    .draw();    

有关代码和演示,请参阅此jsFiddle。

搜索特定列

要搜索特定的列,您可能需要使用自定义搜索功能。

下面的代码显示了在索引为012的表数据值中包含单词AngelicaTokyo的搜索结果。

var table = $('#example').DataTable();
var terms = ['Angelica', 'Tokyo'];    
// Convert terms to lower case
$.each(terms, function(index, value){
   terms[index] = value.toLowerCase();
});
// Enable custom search
$.fn.dataTable.ext.search.push(
   function (settings, data, dataIndex) {
      var isFound = false;
      $.each(data, function (index, value){         
         // Evaluate only first three data values
         if(index === 0 || index === 1 || index === 2){
            // Convert data to lower case
            value = value.toLowerCase();
            $.each(terms, function(termIndex, termValue){
               // If data contains the term
               if (value.indexOf(termValue) !== -1) {
                  isFound = true;
               }
               return !isFound;
            });
         }
         return !isFound;
      });
      return isFound;
   }
);
// Perform search
table.draw();
// Disable custom search
$.fn.dataTable.ext.search.pop();

有关代码和演示,请参阅此jsFiddle。