2014-09-30 20 views
0

我寫了使用jQuery非常簡單的搜索方法,這裏是我的方法:如何讓我的搜索方法在jquery中更好?

function filter() { 
    array = [] 
    // Search For items on Searchbox 
    var name = $(this).find('.info').text().toLowerCase() 
    items = name.match($('#Search').val().toLowerCase()) 

    // Select Valid items 
    if (items != null){ 
     array.push(items) 
     $(this).addClass('Result'); 
     return items; 
    } 
} 

這種方法效果很好,但問題是結果

如果我們有這樣的文字

Enjoy your company 

「享受你的」是true但「你的享受」是false

如何讓我的方法更好地解決此問題,並且如果單詞有不同的順序,我可以捕捉到它?

而且我想如果「享受你的Z」結果用戶搜索應該是false

Here is a jsFiddle

+0

聽起來好像你想要在空格上分割,然後測試名稱是否包含所有這些單詞作爲單獨的單詞。也許在搜索空間和名字空間上分割。 – 2014-09-30 20:49:58

+0

但我應該怎麼做? – Parsoua 2014-09-30 20:54:40

回答

0

您可以考慮使用split()方法來實現此結果。

即使單詞的順序不同,您也可以解決以下更新後的代碼。

 array = []; 
$('#Search').keyup(function (e) {       
    $("body").find(".info").each(function(index){ 
       var matchedIndexes = []; 
       var name = $(this).text().toLowerCase().trim(); 
       var splitedArray = name.split(" "); // to split by space 
       var splitedSearch =$('#Search').val().toLowerCase().trim().split(" "); 

for(var i=0;i<splitedArray.length;i++){ 
    if(i == 0) 
    var matchedLength = 0; 

    for(var j=0;j<splitedSearch.length;j++){ 
     if (splitedArray[i].indexOf(splitedSearch[j]) == 0){ 
      if(splitedArray.length >= splitedSearch.length && matchedIndexes.indexOf(i) == -1){ 
         matchedIndexes.push(i);//To avoid search the same index even after match 
         array.push(splitedArray[i]) 
         $(this).addClass('match'); 
         matchedLength ++; 
      } 
     } 
    } 

    if(matchedLength < splitedSearch.length) 
     $(this).removeClass('match');   
    } 


      }); 

});// keyup 

更新:1
jsfiddle

更新:2
jsfiddle

更新:3
jsfiddle

我希望這會幫助你。

+0

非常感謝你的幫助,一切都是正確的,這裏只是一個問題,那就是性能問題,在你的方法中,如果我搜索Enjoy,它會搜索所有喜歡單詞的字段,但是如果我搜索再享受c將搜索所有領域的享受c,我希望它只在那些享受的領域搜索c字符,而不是在所有其他領域,你能爲我做這個嗎?非常感謝你爲我所做的一切,我希望我能爲你做點什麼:) – Parsoua 2014-10-02 14:28:51

+1

@Parsoua繼續回到ManirajSS並在評論中增加_just one thing_作爲一個問題是不公平的。如果您有其他問題,那麼比[提出新問題](http://stackoverflow.com/questions/ask)的擴展討論不適合他們用於聊天的評論。如果ManirajSS想繼續提供幫助,那麼就討論聊天。 – Taryn 2014-10-03 10:30:57