【问题标题】:How does the matching JS code using indexOf work?使用 indexOf 匹配的 JS 代码是如何工作的?
【发布时间】:2019-12-03 12:15:42
【问题描述】:

我已经设法将一些 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,但我不明白它如何将表格行中的数据与输入的值匹配。

【问题讨论】:

标签: javascript jquery html datatables


【解决方案1】:

它将您发送给函数的值转换为小写,然后查看行中的数据。它也将其转换为小写,并使用 indexof 查看是否有匹配项,此处介绍:How to use IndexOf in JQuery

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

考虑搜索“测试”

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

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

【讨论】:

    【解决方案2】:

    它的作用是

    对于我表中的每一行“结果” 如果我以小写形式查看的所有这些值之一等于我在“searchBar”中以小写形式输入的值,不止一次,那么我找到了它,所以 found = "true"

    【讨论】:

    • 你的回答令人困惑,尤其是关于more than one time的部分。
    【解决方案3】:

    从搜索栏按键事件将被触发,搜索栏的值将传递给搜索功能

    $("#searchBar").keyup(function() {
      searchFunction($(this).val());
    });
    
    function searchFunction(value) {
      //value will contain the value of search bar
      $("#results tr").each(function() {
        //assuming value is not there in tr
        var found = "false";
        //now searching for each tr for value
        $(this).each(function() {
          //converting to lower case and comparing each value with searchbar value
          if (
            $(this)
              .text()
              .toLowerCase()
              .indexOf(value.toLowerCase()) >= 0
          ) {
            found = "true";
          }
        });
        //actual showing/hiding row
        if (found === "true") {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    }
    

    如果需要有关索引的更多信息 https://www.w3schools.com/jsref/jsref_indexof.asp @MattCouthon 如果您还需要什么,请告诉我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2022-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多