按Esc按钮关闭建议列表

时间:2013-12-27 14:33:44

标签: javascript jquery search-engine

当用户按下Esc按钮时,我希望建议列表将被关闭。

我该怎么做?

这是我的代码:

  1. script_suggestion.php:

    <script type="text/javascript">
    
        //document.getElementById("suggestion")
    
        function getSuggestion(q) {
            var ajax;
            if(window.XMLHttpRequest)//for ie7+, FF, Chrome
                ajax = new XMLHttpRequest();//ajax object
            else
                ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
            ajax.onreadystatechange = function() {
                if(ajax.status === 200 && ajax.readyState === 4) {
                    //if result are not there then don't display them
                    if(ajax.responseText === "")
                        document.getElementById("suggestion").style.visibility = "hidden";
                    else {
                        document.getElementById("suggestion").style.visibility = "visible";
                        document.getElementById("suggestion").innerHTML = ajax.responseText;
                    }
                }
            };
            ajax.open("GET", "suggestion.php?q=" + q, false);
            ajax.send();
        }
    </script>
    

  2. PHP代码:

    <?php include 'script_suggestion.php'; include 'script_close_suggestion_box.php'; ?>

  3. 提前致谢。

2 个答案:

答案 0 :(得分:0)

使用此:

var forceClose = false;

function getSuggestion(q) {

    if (!forceClose) {

        var ajax;
        if (window.XMLHttpRequest)//for ie7+, FF, Chrome
            ajax = new XMLHttpRequest();//ajax object
        else
            ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
        ajax.onreadystatechange = function () {
            if (ajax.status === 200 && ajax.readyState === 4) {
                //if result are not there then don't display them
                if (ajax.responseText === "")
                    document.getElementById("suggestion").style.visibility = "hidden";
                else {
                    document.getElementById("suggestion").style.visibility = "visible";
                    document.getElementById("suggestion").innerHTML = ajax.responseText;
                }
            }
        };
        ajax.open("GET", "suggestion.php?q=" + q, false);
        ajax.send();

    }
}

window.document.onkeydown = function (e) {
    if (!e) e = event;
    if (e.keyCode == 27) {
        document.getElementById("suggestion").style.visibility = "hidden";
        forceClose = true;
    }
};

答案 1 :(得分:0)

在getSuggestion()函数后添加此代码:

window.document.onkeyup = function (e)
{
if (!e) e = event;
if (e.keyCode == 27)
document.getElementById("suggestion").style.visibility = "hidden";
}