簡體   English   中英

通過jquery搜索列表(不區分大小寫)

[英]Search Through a list By jquery (with case insensitive)

我正在嘗試通過搜索框搜索列表。 這是我的HTML:

<input type="text" id="query" value=""/>
<ol id="abbreviations" >
<li>Cars</li>
<li>bars</li>
.
.

<ol>

這是我擁有的jQuery代碼:

<script>

var abbrs = {};

$('ol#abbreviations li').each(function(i){
    abbrs[this.firstChild.nodeValue] = i;
});

$('#query').focus().keyup(function(e){
    if(this.value.length >= 2){
        $('ol#abbreviations li').hide();
        var filterBy = this.value;
        for (var abbr in abbrs) {
            if (abbr.indexOf(filterBy) !== -1) {
               var li = abbrs[abbr];
               $('ol#abbreviations li:eq('+li+')').show();
            }
        }       
    } else {
        $('ol#abbreviations li').show();    
    }
    if(e.keyCode == 13) {
        $(this).val('');
        $('ol#abbreviations li').show();
    }   
});
</script>

我的代碼運行良好,但是區分大小寫。 例如,如果我輸入“ Cars”,它將過濾列表,但是如果我輸入“ cars”,則它不起作用。 那么如何使jQuery搜索變得不敏感呢? 我試圖更改var filterBy = this.value.toLowerCase(); ,但不匹配大寫字母。 我該如何運作?

您需要將filterValueabbr都轉換為小寫:

var filterBy = this.value.toLowerCase();
...
if (abbr.toLowerCase().indexOf(filterBy) !== -1) {
...

另請參閱此問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM