2013-03-26 20 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

相關問題