首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使这个Javascript敏感

问如何使这个Javascript敏感
EN

Stack Overflow用户
提问于 2019-08-09 21:46:57
回答 2查看 36关注 0票数 0

我正在制作一个带有文字输入框的网站。

我在JS文件中有一段代码:

代码语言:javascript
复制
$(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”之类的吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-09 22:02:40

你可以的

使用toLowerCase()将所有用户输入转换为小写,因此每次您比较或使用一个单词时,如果没有大写单词,您已经匹配了相同的值。

例如

代码语言:javascript
复制
"Hello".toLowerCase() outputs 'hello'
"hELLo".toLowerCase() outputs 'hello'

在你的代码中

在搜索搜索值的索引之前,确保$(".name", this).text()是小写的。

,所以您的代码将类似于那个

代码语言:javascript
复制
//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/

票数 0
EN

Stack Overflow用户

发布于 2019-08-09 22:19:36

香草版展示了所有的东西是如何结合在一起的。

​

代码语言:javascript
复制
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'));
    }
  }
})
代码语言:javascript
复制
.hide {
  display: none;
}
代码语言:javascript
复制
<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">

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57437466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档