搜索关键字突出显示 [英] Search Keyword Highlighted
本文介绍了搜索关键字突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试突出显示(或设置样式)用户要键入的搜索字词.现在,这将对整个表格单元格进行样式设置.我只想突出显示搜索词,而不是整个td单元.
I am trying to highlight( or style ) the search term that a user will type. Right now this styles the entire table cell. I want just the search term highlighted and not the entire td cell.
我正在显示包含关键字的表行,但是似乎无法在结果中为jQuery('#txtSearch').val()的搜索"关键字设置样式.
I am showing the table rows that contain the keyword, but cannot seem to style the "searched" keyword which is jQuery('#txtSearch').val() within the results...
这就是我所拥有的
jQuery('#' + view + ' tr td:containsNoCase(\'' + jQuery('#txtSearch').val() + '\')').css( "text-decoration", "underline" );
Thx
更完整的代码...
if (jQuery('#txtSearch').val().length > 2) {
jQuery('#' + view + ' tr').hide(); // hide all rows
jQuery('#' + view + ' tr:first').show(); // // show the header row
jQuery('#' + view + ' tr td:containsNoCase(\'' + jQuery('#txtSearch').val() + '\')').parent().show(); // show the matching rows (using the containsNoCase)
jQuery('#' + view + ' tr td:containsNoCase(\'' + jQuery('#txtSearch').val() + '\')').css( "text-decoration", "underline" ); // highlight searchterm
// THIS IS THE ANSWER
function highlightOnly(text) {
$('#' + view + ' td').each(function (i, e) {
var $e = $(e);
$e.html($(e).html().split(text).join('<span class="matching">' + text + '</span>'));
})
}
$('.matching').replaceWith(function () {
return this.innerText;
});
highlightOnly($('#txtSearch').val().toUpperCase());
// THIS IS THE ANSWER
jQuery('#' + view + ' tr:nth-of-type(odd)').css('background', '#fff'); // chg bg
}
推荐答案
尝试使用 :containsNoCase
示例
jQuery.expr[':'].containsNoCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
let term = 'john'
$("div:containsNoCase('" + term + "')")
.html(function() {
return this.innerText.replace(
new RegExp(term + '(?!([^<]+)?<)', "gi"),
'<mark>$&</mark>')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom john Sinclair</div>
<div>J. Ohn</div>
这篇关于搜索关键字突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文