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

bla*_*arg 1 javascript search jquery

我使用jQuery从头开始编写搜索功能,以满足特定需求.它从<span>a中搜索数据<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();
            }
Run Code Online (Sandbox Code Playgroud)

JSFiddle在这里

Dan*_*mms 5

问题是你的if语句忽略了第一个字符,因为第一个字符在索引0处.

if (currentAuthor.search(searchBox1) > 0)
Run Code Online (Sandbox Code Playgroud)

应该:

if (currentAuthor.search(searchBox1) >= 0)
Run Code Online (Sandbox Code Playgroud)

如果你是区分大小写,你需要申请toUpperCase()toLowerCase().

if (currentAuthor.ToUpperCase().search(searchBox1.toUpperCase()) >= 0)
Run Code Online (Sandbox Code Playgroud)