2014-01-16 35 views
1

我有一個網站,顯示英雄聯盟所有圖標連續。其中一個看起來是這樣的:如何使用Javascript進行自動搜索過濾器?

<div class = "champion"> 
<p>Aatrox 
    <img class = "face_left" src = "images/small/Aatrox.png"> 
    <div class = "name" onmouseover="if(champ1=='') preview1('Aatrox', 'Aatrox')" onmouseout="if(champ1=='')restoreAvatar1()" onClick="champ1 = 'Aatrox'; preview1('Aatrox', 'Aatrox')"> 
    </div> 
    </p> 
</div> 

而且我希望有他們上面搜索欄,當你在冠軍的名字開始打字,它會自動啓動過濾掉不適合被搜索的內容冠軍。現在,我確實找到了這個Javascript代碼片段,並且我已經搞定了它,並且在更簡單的場景中工作,其中我只有一個div和ap標籤,但由於某些原因,所有這些div都不想過濾任何東西。這是搜索欄和JS的樣子:

<input type="text" id="search" placeholder="Type to search"> 

var $rows = $('.champion p'); 
$('#search').keyup(function() { 
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase(); 

    $rows.show().filter(function() { 
     var text = $(this).text().replace(/\s+/g, ' ').toLowerCase(); 
     return !~text.indexOf(val); 
    }).hide(); 
}); 

有沒有什麼辦法讓這個代碼過濾掉裏面的一切,整個「狀元」的div?

+0

像http://jsfiddle.net/arunpjohny/mQH5z/1/? –

回答

2

嘗試

if (!RegExp.escape) { 
    RegExp.escape = function (s) { 
     return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") 
    }; 
} 

jQuery(function(){ 
    var $rows = $('.champion'); 
    $('#search').keyup(function() { 
     var regex = new RegExp(RegExp.escape($.trim(this.value).replace(/\s+/g, ' ')), 'i') 
     $rows.hide().filter(function() { 
      var text = $(this).text().replace(/\s+/g, ' '); 
      return regex.test(text) 
     }).show(); 
    }); 
}); 

演示:Fiddle

+0

然後你可以使用'data- *'屬性參見http://jsfiddle.net/arunpjohny/mQH5z/2/ –