0

我正在尝试通过搜索框搜索列表。这是我的 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>

我的代码运行良好,但区分大小写。例如,如果我输入“汽车”,它将过滤列表,但如果我输入“汽车”,它就不起作用。那么我怎样才能让这个 jQuery 搜索变得不敏感呢?我试图改变var filterBy = this.value.toLowerCase();,但它不会匹配大写字母。我怎样才能让它工作?

4

1 回答 1

1

您需要将filterValue和都转换为小写abbr

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

另请参阅此 SO 问题

于 2013-09-29T14:02:53.940 回答