jquery突出显示表

时间:2017-06-08 05:59:43

标签: jquery highlight

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

示例:如果我搜索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);

    });
});

})();

2 个答案:

答案 0 :(得分:1)

使用toLowerCase()更改如下所示: -

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;
    }
}

工作小提琴: - https://jsfiddle.net/c612ak5d/

答案 1 :(得分:1)

使用toLowerCase()即可实现:

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