jQuery 插件 DataTables:如何突出显示当前搜索文本?
Posted
技术标签:
【中文标题】jQuery 插件 DataTables:如何突出显示当前搜索文本?【英文标题】:jQuery plugin DataTables: How to highlight the current search text? 【发布时间】:2011-02-08 08:29:40 【问题描述】:我已经开始使用 jQuery(v1.4.2) 的 DataTables 插件 (v1.6.2),请问您是否知道 设置或插件,让我可以在过滤的行上突出显示搜索文本框中使用的文本。
提前谢谢你
【问题讨论】:
【参考方案1】:我不得不建议highlight plugin :)
我现在在大致相同的情况下使用它,到目前为止它没有给我带来任何问题。
用法很简单:
$("#myTable").highlight($("#searchBox").val());
只需将高亮 CSS 类放入您想要的样式表样式中即可:
.highlight background-color: yellow
【讨论】:
是的,这是一个很棒的小插件,而且代码很清晰,是如何做这类事情的一个很好的例子。 但是数据表中默认没有id为searchBox的元素。你是怎么添加的? @iamrohitbanga - 它只是您在页面上的一些<input type="text" />
元素,可以触发此 onchange 或 keyup、按钮单击...无论您追求什么 UI。
更好:$table.on('search.dt', function () $table.on('draw.dt', function() var api = $table.api() ; $('tbody', $table).highlight(api.search()); ) );
@SebastiaanHilbers 这适用于新的 API: $table.on('search.dt', function () $(this).dataTable().on('draw.dt', function ( ) var term = $(this).dataTable().api().search(); $('tbody', this).highlight(term); ); );【参考方案2】:
我知道这个问题现在已经超过 6 年了,这里的答案可能会在你提问时对你有所帮助。但是对于仍在寻找这个的人来说,有一个新插件可以将 mark.js(一个 javascript 关键字突出显示)集成到 DataTables 中:datatables.mark.js。
用法很简单:
$("table").DataTables(
mark: true
);
这里是一个例子:https://jsfiddle.net/julmot/buh9h2r8/
这是最简洁的方式,并且还为您提供了任何给定解决方案都没有提供给您的选项。
现在有一个官方的 DataTables blog article 可用。
【讨论】:
我确认这也有效并且是一种有效的方法。【参考方案3】:您可以通过应对此内容来使用此功能:
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings)
oSettings.oPreviousSearch.oSearchCaches = ;
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull)
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch)
searchStrings.push(oSettings.oPreviousSearch.sSearch);
// Individual column search option object
// If there are individual column search strings, add them to the search string array
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0))
for (var i in oSettings.aoPreSearchCols)
if (oSettings.aoPreSearchCols[i].sSearch)
searchStrings.push(oSettings.aoPreSearchCols[i].sSearch);
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0)
var sSregex = searchStrings.join("|");
if (!cache[sSregex])
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++)
regRules += "|("+ regRulesSplit[i] +")";
regRules += ")";
// This regex will avoid in html matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
var regex = cache[sSregex];
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i)
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
if (aData[j])
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex))
this.innerHTML = aData[j].replace( regex, function(matched)
return "<span class='filterMatches'>"+matched+"</span>";
);
// Otherwise reset to a clean string
else
this.innerHTML = aData[j];
);
return nRow;
, 'row-highlight');
return this;
;
里面:
dataTables.search-highlight.js
这样称呼它:
<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.search-highlight.js"></script>
<script type="text/javascript">
$(document).ready(function()
var oTable = $('#example').dataTable();
oTable.fnSearchHighlighting();
);
</script>
并将此代码添加到您的 css 文件中:
.filterMatches
background-color: #BFFF00;
【讨论】:
代码有很多错误,因为它无法处理将 json 数据加载到数据表时的情况,无论是否有服务器端处理。【参考方案4】:<link href="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.js"></script>
$("#tableId").dataTable(
mark: true
);
【讨论】:
【参考方案5】:你可以使用下面的add on
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings)
// Initialize regex cache
oSettings.oPreviousSearch.oSearchCaches = ;
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull)
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch)
searchStrings.push(oSettings.oPreviousSearch.sSearch);
// Individual column search option object
// If there are individual column search strings, add them to the search string array
// searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
var searchTxt = $('input[type="search"]').val();
// console.log("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0))
for (var i in oSettings.aoPreSearchCols)
if (oSettings.aoPreSearchCols[i].sSearch)
searchStrings.push(searchTxt);
// Create the regex built from one or more search string and cache as necessary
/*if (searchStrings.length > 0)
var sSregex = searchStrings.join("|");
if (!cache[sSregex])
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
var regex = cache[sSregex];
*/
if (searchStrings.length > 0)
var sSregex = searchStrings.join("|");
if (!cache[sSregex])
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++)
regRules += "|("+ regRulesSplit[i] +")";
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
var regex = cache[sSregex];
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i)
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
// console.log("data "+ aData[j] + " j " + j);
// console.log("data 1 "+ nRow);
if (aData)
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex))
//console.log("here :: "+$(this).text());
this.innerHTML = $(this).text().replace( regex, function(matched)
return "<span class='filterMatches'>"+matched+"</span>";
);
// Otherwise reset to a clean string
else
this.innerHTML = $(this).text();//aData[j];
);
return nRow;
, 'row-highlight');
return this;
;
这个解决方案对我有用。 注意:目前它不支持单列过滤,但您只需在代码中取消注释即可。
searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
我已经使用数据表 1.10.2 和 jquery 1.9.2 版本对此进行了测试。
【讨论】:
【参考方案6】:这个插件有更好的突出搜索文本的功能。如果您在对话框中创建了数据表,则在对话框重新打开时您需要重新初始化数据表。
在 DatatableHighlighter.js 中
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings)
// Initialize regex cache
oSettings.oPreviousSearch.oSearchCaches = ;
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull)
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch)
searchStrings.push(oSettings.oPreviousSearch.sSearch);
// Individual column search option object
// If there are individual column search strings, add them to the search string array
// searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
var searchTxt = $('input[type="search"]').val();
// console.log("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0))
for (var i in oSettings.aoPreSearchCols)
if (oSettings.aoPreSearchCols[i].sSearch)
searchStrings.push(searchTxt);
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0)
var sSregex = searchStrings.join("|");
if (!cache[sSregex])
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++)
regRules += "|("+ regRulesSplit[i] +")";
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
//cache[sSregex] = new RegExp(regRules+"", 'ig');
var regex = cache[sSregex];
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i)
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
if (aData)
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex))
//For removing previous added <span class='filterMatches'>
var element = $(this);//convert string to JQuery element
element.find("span").each(function(index)
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
).remove();
var newString = element.html();//get back new string
this.innerHTML = newString.replace( regex, function(matched)
return "<span class='filterMatches'>"+matched+"</span>";
);
// Otherwise reset to a clean string
else
//For removing previous added <span class='filterMatches'>
var element = $(this);//convert string to JQuery element
element.find("span").each(function(index)
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
).remove();
var newString = element.html();
this.innerHTML = newString;//$(this).html()//$(this).text();
);
return nRow;
, 'row-highlight');
return this;
;
然后这样称呼它......
$("#button").click(function()
dTable = $('#infoTable').dataTable("bPaginate": false,"bInfo" : false,"bFilter": true,"bSort":false, "autoWidth": false,"destroy": true,
"columnDefs": [
"width": "35%", "targets": 0 ,
"width": "65%", "targets": 1
]);
$(".dataTables_filter input[type='search']").val('');
$("span[class='filterMatches']").contents().unwrap();
dTable.fnSearchHighlighting();
$("span[class='filterMatches']").contents().unwrap();
$("#AboutDialog").dialog('open');
);
【讨论】:
以上是关于jQuery 插件 DataTables:如何突出显示当前搜索文本?的主要内容,如果未能解决你的问题,请参考以下文章
如何在DataTables 1.10中使用JQuery DataTables“input”插件
如何更改 DataTables jQuery 插件的分页按钮数量
如何从 Datatables jQuery 插件中提取过滤后的数据?
如何使用 jQuery DataTables 插件实现服务器端处理?