javascript - 使用 indexOf 匹配的 JS 代码是如何工作的?
问题描述
我已经设法将一些 JS 复制到我的文档中,并且可以正常工作。但我不完全明白它是如何做到的。
它是一种搜索功能,用于匹配表中的数据并隐藏任何不匹配的行。
但我不明白实际搜索和匹配的活动代码行。有人会解释吗?
$('#searchBar').keyup(function() {
searchFunction($(this).val());
});
function searchFunction(value) {
$('#results tr').each(function() {
var found = 'false';
$(this).each(function() {
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
});
if (found === 'true') {
$(this).show();
} else {
$(this).hide();
}
})
};
这是我无法理解的这条线:
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
我了解它如何将变量更改为 true,但我不明白它如何将表行中的数据与输入的值相匹配。
解决方案
它将您发送给函数的值转换为小写,然后查看行中的数据。它也将其转换为小写,并查看是否使用 indexof 匹配,这在此处进行了介绍:如何在 JQuery 中使用 IndexOf
基本上,indexOf() 方法返回指定值在字符串中第一次出现的位置。如果要搜索的值不存在,则返回 -1。
考虑搜索“测试”
var str = "Hello this is a test";
var n = str.indexOf("test");
n 的结果将是:16,ergo,就像在您的脚本中一样,大于 0...并且“找到”
推荐阅读
- python - 分别修改过滤器中的特定行熊猫
- android - @{View.GONE}/@{View.INVISIBLE} 不会改变 xml 中的任何内容
- python - 使用用户输入进行验证码挑战的 Python 网络抓取
- react-native - React Native:如何等到一系列 setState 函数返回后再执行下一段代码?
- python - 未加载库:导入 scanpy 和表时 @rpath/libhdf5.103.dylib
- gruntjs - 对象对象不是 PostCSS 插件 | PostCSS 自动前缀
- python - python多线程/ 3+参数
- html - 为什么 .css 文件没有更改字体系列?
- python - 断言输入的最佳方式是通常隐藏的内置类
- spring - 为什么从 OpenFeign 请求中检索到 Spring Data Rest 端点的嵌套对象为 null?