0

我有一个简单的数据库搜索脚本,当用户在搜索字段中键入时,它会显示搜索结果列表。该脚本工作正常,只是它仅在用户键入第二个字母后才开始工作。我希望它在用户在搜索查询中输入第一个字母时开始工作。例如,如果我正在搜索“娃娃”,那么当用户在搜索字段中键入字母“d”时,我希望显示搜索结果。目前,这仅在用户输入“do”后才开始发生。请给我任何你可能有的建议。

jQuery:

<script type="text/javascript">
$(function(){ 
    var index = -1;
    $(document).on('keyup','#searchField',function(e){
        if (e.keyCode == 38){ // up arrow
            index = (index == 0) ? 0 : index - 1;
            $('tr.search_row').removeClass('highlight_color');
            $('tr.search_row:eq(' + index + ')').addClass('highlight_color');
            return false;
        }
        else if (e.keyCode == 40){ // down arrow
            index = (index + 1 >= $('tr.search_row').length) ? $('tr.search_row').length - 1 : index + 1;
            $('tr.search_row').removeClass('highlight_color');
            $('tr.search_row:eq(' + index + ')').addClass('highlight_color');
            return false;
        }
        else
        {
            var str = $('#searchField').val();
            searchScript(str);
        }
        index = -1;
    }); 
});
</script>
4

2 回答 2

0

I'm able to see the the query getting called on the first letter itself. I'm suspecting that the problem might be in the searchScript function. Check this fiddle.

 Post more details about the searchScript function if you are still seeing the error.
于 2013-05-12T18:48:04.193 回答
0

U can use

.bind("change keyup input",function() { });

http://solicitingfame.com/2011/11/09/jquery-keyup-vs-bind/

于 2013-05-12T16:30:12.160 回答