【问题标题】:Why does my search function only match when I miss off the first character?为什么我的搜索功能只在我错过第一个字符时匹配?
【发布时间】:2013-03-26 09:57:27
【问题描述】:

我使用 jQuery 从头开始​​编写了一个搜索功能,以满足特定需求。它从<div><span> 中搜索数据,然后在与文本框中的字符串不匹配时隐藏<div>

我遇到的问题是它会识别字符串但不能识别第一个字符。它也区分大小写,这不是我想要包含的功能。

 //Grab ID of current recordContainer
            var currentID = $(this).attr('id');
        // Add hash tag so it can be used as an ID call
            var currentID2 = ("#" + currentID);
        //Grab data from author span in current recordContainer
            var currentAuthor = $(this).children('span.listLeadAuthor').text();
        //If current author matches anything in the search box then keep it visible
            if (currentAuthor.search(searchBox1) > 0)
            {
                    $(currentID2).show();
                    count++;
            }
        //If search box is empty keep it visible
            else if (searchBox1 === "")
            {
                    $(currentID2).show();
            }

JSFiddle Here

【问题讨论】:

  • 请复制粘贴问题中的代码。
  • currentAuthor.search(searchBox1) !== -1

标签: javascript jquery search


【解决方案1】:

问题是您的 if 语句忽略了第一个字符,因为第一个字符位于索引 0 处。

if (currentAuthor.search(searchBox1) > 0)

应该是:

if (currentAuthor.search(searchBox1) >= 0)

如果您需要区分大小写,则需要申请 toUpperCase()toLowerCase()

if (currentAuthor.ToUpperCase().search(searchBox1.toUpperCase()) >= 0)

【讨论】:

  • 这很好,但它仍然区分大小写。
  • 找到了解决方法 if (currentAuthor.search(new RegExp(searchBox1, "i")) !== -1)
【解决方案2】:

我遇到的问题是它会识别字符串但不能识别第一个字符。

你的问题就在这里:

if (currentAuthor.search(searchBox1) > 0)
JS 中的

String.search 为您提供第一个匹配项的 位置。如果那是文本的开头,那么它就是0

找不到匹配项的返回值不是0,而是-1

【讨论】:

    猜你喜欢
    • 2012-05-15
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多