当用户按下Esc
按钮时,我希望建议列表将被关闭。
我该怎么做?
这是我的代码:
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>
PHP代码:
<?php
include 'script_suggestion.php';
include 'script_close_suggestion_box.php';
?>
提前致谢。
答案 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";
}