首页 > 解决方案 > 使用 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,但我不明白它如何将表行中的数据与输入的值相匹配。

标签: javascriptjqueryhtmldatatables

解决方案


它将您发送给函数的值转换为小写,然后查看行中的数据。它也将其转换为小写,并查看是否使用 indexof 匹配,这在此处进行了介绍:如何在 JQuery 中使用 IndexOf

基本上,indexOf() 方法返回指定值在字符串中第一次出现的位置。如果要搜索的值不存在,则返回 -1。

考虑搜索“测试”

var str = "Hello this is a test";
var n = str.indexOf("test");

n 的结果将是:16,ergo,就像在您的脚本中一样,大于 0...并且“找到”


推荐阅读