0

我编写了一个通过使用 jquery 搜索来过滤表数据的代码。但是搜索是区分大小写的。我需要使它不区分大小写。比如如果我搜索a它会同时显示aA字符串。表格代码是 -

<input id="searchInput" value="Type To Filter">
<br/>
<table>
    <thead>
        <tr>
            <th>Column1</th>
            <th>Column2</th>
        </tr>
    </thead>
    <tbody id="fbody">
        <tr>
            <td>Cat</td>
            <td>one</td>
        </tr>
        <tr>
            <td>dog</td>
            <td>two</td>
        </tr>
        <tr>
            <td>cat</td>
            <td>Three</td>
        </tr>
        <tr>
            <td>moose</td>
            <td>four</td>
        </tr>
        <tr>
            <td>mouse</td>
            <td>five</td>
        </tr>
        <tr>
            <td>dog</td>
            <td>six</td>
        </tr>
    </tbody>
</table> 

JS代码是-

$("#searchInput").keyup(function () {
    //split the current value of searchInput
    var data = this.value.split(" ");
    //create a jquery object of the rows
    var jo = $("#fbody").find("tr");
    if (this.value == "") {
        jo.show();
        return;
    }
    //hide all the rows
    jo.hide();

    //Recusively filter the jquery object to get results.
    jo.filter(function (i, v) {
        var $t = $(this);
        for (var d = 0; d < data.length; ++d) {
            if ($t.is(":contains('" + data[d] + "')")) {
                return true;
            }
        }
        return false;
    })
    //show the rows that match.
    .show();
}).focus(function () {
    this.value = "";
    $(this).css({
        "color": "black"
    });
    $(this).unbind('focus');
}).css({
    "color": "#C0C0C0"
});
4

2 回答 2

4

替换这个条件:

if ($t.is(":contains('" + data[d] + "')")) {
    return true;
}

在这种情况下:

if ($t.text().toLowerCase().indexOf(data[d].toLowerCase()) > -1) {
    return true;
}

jsFiddle 示例

于 2013-11-06T16:33:33.263 回答
1

尝试

RegExp.escape = function (s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};


...
jo.filter(function (i, v) {
    var $t = $(this);
    for (var d = 0; d < data.length; ++d) {
        var regex = new RegExp(RegExp.escape(data[d]), 'i')
        if (regex.test($t.text())) {
            return true;
        }
    }
    return false;
})
于 2013-11-06T16:22:45.800 回答