javascript - 为什么我的搜索功能只在我错过第一个字符时才匹配?

标签 javascript jquery search

我使用 jQuery 从头开始​​编写了一个搜索功能,以满足特定需求。它从 <span> 中搜索数据的 <div>然后隐藏 <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

最佳答案

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

if (currentAuthor.search(searchBox1) > 0)

应该是:

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

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

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

关于javascript - 为什么我的搜索功能只在我错过第一个字符时才匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634074/

相关文章:

javascript - 将 ajax 调用的响应存储在 ember 中

jquery - 标签内容 : Left Border Disconnected from Tabs Above - html CSS jQuery

javascript - 在数组中查找时间,如果没有找到,则选择上一个

.net - 如何搜索允许标记的数据库列?

javascript - 在 react 中显示/隐藏特定的 <div>

javascript - YouTube的jQuery获取视频页面HTML

jquery - 使用 django 生成文件以使用 javascript/jQuery 下载

javascript - 通过两个标签小部件作为下拉菜单在博客平台中搜索

mysql - 在 Mysql 中使用特殊字符搜索

javascript - 什么是构建面向 Web 和本地语言的游戏框架的好平台?