我正在制作一个带有文字输入框的网站。
我在JS文件中有一段代码:
$(document).ready(function() {
$("#filterTextBox").on("keyup", function () {
var search = this.value;
$(".person").show().filter(function () {
return $(".name", this).text().indexOf(search) < 0;
}).hide();
});
});有了这个,当我搜索"hello“时,它就找不到"Hello”这个名字了,我可以让它不管是"Hello“还是"hELLo”之类的吗?
发布于 2019-08-09 22:02:40
你可以的
使用toLowerCase()将所有用户输入转换为小写,因此每次您比较或使用一个单词时,如果没有大写单词,您已经匹配了相同的值。
例如
"Hello".toLowerCase() outputs 'hello'
"hELLo".toLowerCase() outputs 'hello'在你的代码中
在搜索搜索值的索引之前,确保$(".name", this).text()是小写的。
,所以您的代码将类似于那个
//hide all the elements except for the matches
$(document).ready(function() {
$("#filterTextBox").on("keyup", function () {
var search = this.value.toLowerCase();
$(".person").show().filter(function () {
return $('.name', this).text().toLowerCase().indexOf(search)<0;
}).hide();
});
});谢谢@mark.hch的代码https://jsfiddle.net/yd9k12bz/
发布于 2019-08-09 22:19:36
香草版展示了所有的东西是如何结合在一起的。
const getPeople = () => document.querySelectorAll('.person');
document.addEventListener('keyup', ({ target }) => {
if (target.matches('#search')) {
const searchFor = target.value.toLowerCase();
if (searchFor.length > 0) {
getPeople().forEach(p => {
if (p.innerText.toLowerCase().includes(searchFor)) {
p.classList.remove('hide');
} else {
p.classList.add('hide')
}
});
} else {
// Show all
getPeople().forEach(p => p.classList.remove('hide'));
}
}
}).hide {
display: none;
}<div class="person">Paul T</div>
<div class="person">John B</div>
<div class="person">David C</div>
<div class="person">Lisa A</div>
<div class="person">Claire W</div>
<div class="person">Paul W</div>
<div class="person">John F</div>
<div class="person">David S</div>
<div class="person">Lisa R</div>
<div class="person">Claire B</div>
<input type="text" id="search">
https://stackoverflow.com/questions/57437466
复制相似问题