jquery 突出显示 table 中的搜索文本

jquery highlight search text in table

我使用下面的代码来突出显示 table 中的文本此代码工作正常,但我有一个问题,它对大写字母和小写字母敏感

示例: 如果我搜索 test

这样的词

如果我输入大写 TestTEST 我找不到这个词 只有当我像那样输入 test 时我才找到

我该如何解决这个问题??

我希望如果我输入大写字母或小写字母,则单词会突出显示。

此代码:

(function () {
var removeHighlight = function () {
    $('span.highlight').contents().unwrap();
};

var wrapContent = function (index, $el, text) {
    var $highlight = $('<span class="highlight"/>')
        .text(text.substring(0, index));
    //console.log(text.substring(0, index));
    var normalText = document.createTextNode(text.substring(index, text.length));
    //console.log(index, $highlight.text(), normalText);
    $el.html($highlight).append(normalText);
};

var highlightTextInTable = function ($tableElements, searchText) {
    // highlights if text found (during typing)
    var matched = false;
    //remove spans
    removeHighlight();

    $.each($tableElements, function (index, item) {
        var $el = $(item);
        if ($el.text().search(searchText) != -1 && !matched) {
            //console.log("matched", $el, $el.html());
            wrapContent(searchText.length, $el, $el.html());
            //console.log(searchText, $el.text());
            if (searchText.toLowerCase() == $el.text().toLowerCase()) {
                // found the entry
                //console.log("matched");
                matched = true;
            }
        }
    });
};

$(function () {
    //load table into object
    var $tableRows = $('table td');
    var $tableElements = $tableRows.children();

    console.log($tableRows, $tableElements);

    $('#search').on('keyup', function (e) {
        var searchText = $(this).val();

        if (searchText.length == 0) {
            // catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
            removeHighlight(); // remove last remaining highlight
            return;
        }
        //findTextInTable($tableElements, searchText);

        highlightTextInTable($tableElements, searchText);

    });
});

})();

使用 toLowerCase() anc 更改如下:-

if ($el.text().toLowerCase().search(searchText.toLowerCase()) != -1 && !matched) {
    //console.log("matched", $el, $el.html());
    wrapContent(searchText.length, $el, $el.html());
    console.log($el.text().toLowerCase());
    if (searchText.toLowerCase() == $el.text().toLowerCase()) {
        // found the entry
        //console.log("matched");
        matched = true;
    }
}

Workinf fiddle:- https://jsfiddle.net/c612ak5d/

使用toLowerCase()你可以实现它:

if (searchText.toLowerCase() == $el.text().toLowerCase()) {
    // found the entry
   // console.log("matched");
   matched = true;
}