我有一个用于通过使用jquery进行搜索来过滤表数据的代码。但搜索区分大小写。我需要让它不区分大小写。例如,如果我搜索a
,它将同时显示a
和A
字符串。表格代码是 -
<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"
});
答案 0 :(得分:4)
替换此条件:
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
有这个条件:
if ($t.text().toLowerCase().indexOf(data[d].toLowerCase()) > -1) {
return true;
}
<强> jsFiddle example 强>
答案 1 :(得分: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;
})