2013-03-26 16 views
1

我已经使用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

+1

请复制粘贴问题中的代码。 – JJJ 2013-03-26 09:59:07

+0

'currentAuthor.search(searchBox1)!== -1' – 2013-03-26 10:04:48

回答

5

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

if (currentAuthor.search(searchBox1) > 0) 

应该是:

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

如果你以后的情况下敏感度,您将需要应用toUpperCase()toLowerCase()

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

这很棒,但它仍然区分大小写。 – blarg 2013-03-26 10:05:00

+0

找到了修复程序 if(currentAuthor.search(new RegExp(searchBox1,“i”))!== -1) – blarg 2013-03-26 10:19:05

2

我是它将识别字符串而不是第一个字符的问题。

你的问题就在这里:

if (currentAuthor.search(searchBox1) > 0) 

String.search在JS让你在第一场比赛的位置。如果这是正确的文本的开始,那么它是0

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

相关问题