8

我试图实现一个类似 facebook 的搜索,它将在用户输入时返回结果(自动完成),这是我正在使用的 jquery 代码:

$(document).ready(function(){
    $("#searchField").keyup(function() 
    {
        var searchbox = $(this).val();
            if(searchbox=='')
            {
            $("#searchDisplay").html('').hide();
            }
            else
            {
                $.ajax({
                url: "ajax/?do=search_users&q="+ searchbox+"",
                //data: dataString,
                cache: false,
                    success: function(html)
                    {
                        $("#searchDisplay").html(html).show();
                    }
                });
            }return false;    
    });
});

$("#searchField").focusout(function(){
    $("#searchDisplay").slideUp();
});

$("#searchField").focus(function(){
    if($("#searchDisplay").html() != ''){
        $("#searchDisplay").slideDown();
    }
});

返回结果为 div 结构。我不知道该怎么做是让用户使用键盘上的 [UP] 和 [DOWN] 键浏览结果,然后按 [ENTER] 按钮选择结果。

额外信息

这是display_box

<div id="searchDisplay">
                echo '<a href="'.$_config['http'].$username.'"><div class="display_box" align="left">';
                echo '<img src="'.$img.'"  style="width:25px; float:left; margin-right:6px" />';
                echo $name.'<br/>';
                echo '<span style="font-size:9px; color:#999999">'.$username.'</span></div></a>';
</div>

HTML 标记

    <a href="ahoora"><div class="display_box" align="left">
    <img src="http://domain.com/upload/thumbs/ahoora_1336145552.jpg" style="width:25px; float:left; margin-right:6px">
<strong>a</strong>hour<strong>a</strong><br>
<span style="font-size:9px; color:#999999"><strong>a</strong>hoor<strong>a</strong></span>
</div></a>

每个结果都有上面的 html 代码,它们都被加载到一个<div>带有id=searchDisplay.

*注意php echo部分有一个while循环,上面的代码只是html的样子(searchDisplay和结果不在同一个页面,查看jquery代码)。

4

5 回答 5

4

有一个 jQuery 插件可以将动作绑定到键盘快捷键。我用它来导航使用光标键的项目列表:

https://github.com/jeresig/jquery.hotkeys

用插件定义快捷键就这么简单:

$(document).bind('keydown', 'ctrl+a', fn);
于 2012-05-07T00:16:49.893 回答
4

jQuery UI 自动完成很好地处理了这个功能,没有任何额外的代码:

http://jqueryui.com/demos/autocomplete/

请参阅此 url 上的演示以获取快速入门。

于 2012-05-09T04:45:16.900 回答
2

我已经稍微改写了你的代码,应该做同样的事情,只是更容易阅读和更有效率:

$("#searchField").on({
    keyup : function(e) {
        var code = (e.keyCode ? e.keyCode : e.which),
            searchbox = this.value,
            Sdisplay = $("#searchDisplay");
        if(searchbox=='') {
            Sdisplay.html('').hide();
        }else{
           $.ajax({
            url: "ajax/?do=search_users&q="+ searchbox+"",
            //data: dataString,
            cache: false
           }).done(function(html) {
               Sdisplay.html(html).show();
           });
        }
    },
    focus: function() {
        $("#searchDisplay").slideDown();        
    },
    blur: function() {
        $("#searchDisplay").slideUp();
    }
});

至于搜索结果,您可以只定位每个<a>元素,但您的网站上可能还有其他<a>元素,所以我会添加一个包装器以使它们更容易定位,您可以使用 jQuery 的 wrap() 和 each( ) 函数,但如果可能的话,最简单的方法是将它添加到您的 PHP 中,如下所示:

<div id="searchDisplay">
    echo '<div class="wrapper">';
    echo '<a href="'.$_config['http'].$username.'">';
    echo '<div class="display_box" align="left">';
    echo '<img src="'.$img.'" style="width:25px; float:left; margin-right:6px" />';
    echo $name.'<br/>';
    echo '<span style="font-size:9px; color:#999999">'.$username.'</span></div></a>';
    echo '</div>';
</div>

至于使用向上/向下箭头键切换结果并将位置更改为搜索结果,我会做类似的事情(注意使用之前添加的 .wrapper 类):

if (code == 40 || code == 38 || code == 13) {//arrow keys and enter
    if ($("#searchDisplay").is(':visible')) {
        switch (code) {
            case 40: //arrow down
               act = act > $('.wrapper').length-2 ? 0 : act+1;
               $(".wrapper").removeClass('active').eq(act).addClass('active');
            break;
            case 38: //arrow up
               act = act < 1 ? $('.wrapper').length-1 : act-1;
               $(".wrapper").removeClass('active').eq(act).addClass('active');
            break;
            case 13: //enter key
               var ViElms = $('.wrapper').filter(':visible').filter('.active').length;
               if (ViElms) { //if there are any search results visible with the active class
                   var link = $('.wrapper').eq(act).find('a')[0].href;
                   window.location.href = link;
               }
           break;
     }
}

现在要缓存一些选择器,并将其与keyup函数放在一起,请执行以下操作:

$(document).ready(function() {
    var act = -1;
    $("#searchField").on({
        keyup: function(e) {
            var code = (e.keyCode ? e.keyCode : e.which),
                searchbox = this.value,
                Sdisplay = $("#searchDisplay"),
                wrappers = $('.wrapper'); //there's that class again
            if (searchbox == '') {
                Sdisplay.html('').hide();
            } else {
                Sdisplay.show();
                if (code == 40 || code == 38 || code == 13) { //do not search on arrow keys and enter
                    if (Sdisplay.is(':visible')) {
                        switch (code) {
                        case 40: //arrow down
                            act = act > wrappers.length - 2 ? 0 : act + 1;
                            wrappers.removeClass('active').eq(act).addClass('active');
                            break;
                        case 38: //arrow up
                            act = act < 1 ? wrappers.length - 1 : act - 1;
                            wrappers.removeClass('active').eq(act).addClass('active');
                            break;
                        case 13: //enter
                            var ViElms = wrappers.filter(':visible').filter('.active').length;
                            if (ViElms) { //if there are any search results visible with the active class
                               var link = wrappers.eq(act).find('a')[0].href;
                               window.location.href = link;
                            }
                            break;
                        }
                    }
                } else { //do search
                    $.ajax({
                       url: "ajax/?do=search_users&q="+ searchbox+"",
                       //data: dataString,
                       cache: false
                    }).done(function(html) {
                       Sdisplay.html(html).show();
                    });
                }
            }
        },
        focus: function() {
            $("#searchDisplay").slideDown();
        },
        blur: function() {
            $("#searchDisplay").slideUp();
        }
    });
});​

这是一个演示

于 2012-05-09T15:10:18.610 回答
2

试试这个代码......我从我的书签集合中找到

http://www.9lessons.info/2009/06/autosuggestion-with-jquery-ajax-and-php.html

于 2012-05-03T09:31:01.943 回答
1

尝试这个。滚动列表并在您越过开头/结尾时返回顶部/底部。

<script type="text/javascript">
<!--
$(document).ready(function() {
    $("#searchbox").on("keydown",handleKeys);
});
function handleKeys(e) {

    var keyCode=e.keyCode? e.keyCode : e.charCode;
    if (keyCode==40 && $("a.activeoption").length==0) {
        $("a").eq(0).addClass("activeoption");
    } else if (keyCode==40 && $("a.activeoption").length!=0) {
        $("a.activeoption").next().addClass("activeoption");
        $("a.activeoption").eq(0).removeClass("activeoption");
        if ($("a.activeoption").length==0)
            $("a").eq(0).addClass("activeoption");
    } else if (keyCode==38 && $("a.activeoption").length==0) {
        $("a").last().addClass("activeoption");
    } else if (keyCode==38 && $("a.activeoption").length!=0) {
        var toSelect=$("a.activeoption").prev("a");
        $("a.activeoption").eq(0).removeClass("activeoption");
        toSelect.addClass("activeoption");
        if ($("a.activeoption").length==0)
            $("a").last().addClass("activeoption");
    } else if (keyCode==13) {
        window.location=$("a.activeoption")[0].href;
    }
}
//-->
</script>

演示:http ://www.dstrout.net/pub/keyscroll.htm

于 2012-05-09T02:57:14.907 回答