突出显示的搜索关键字

时间:2019-06-12 14:24:27

标签: javascript jquery css

我正在尝试突出显示(或设置样式)用户要输入的搜索字词。现在,这将为整个表格单元格设置样式。我只想突出显示搜索词,而不是整个td单元。

我正在显示包含关键字的表行,但似乎无法在结果中设置jQuery('#txtSearch')。val()的“搜索”关键字的样式...

这就是我所拥有的

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

}

3 个答案:

答案 0 :(得分:0)

这是操作方法的伪代码:

const searchedText = ...;
const foundCell = ...;
const updatedText = `<span class="HIGHLIGHT">${searchedText}</span>`
const newText = foundCell.text().replace(RegExp(searchedText, "gi"), updatedText);
foundCell.html(newText);

答案 1 :(得分:0)

您可以在以下元素中突出显示特定单词

JS

function hiliter(word, element) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="highlight">' + word + '</span>';
    element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
elem = //your element
hiliter(jQuery('#txtSearch').val(),elem );

CSS

.highlight{
  text-decoration : underline
}

答案 2 :(得分:0)

尝试使用: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>

相关问题