我正在创建一个建议搜索框,当我向上或向下浏览建议时,它会在短时间内更改为新的高亮类,然后恢复为默认类。问题似乎是当我用这条线调用我的 php 时searchReq.open("GET", '/search/ajax-suggest.php?search=' + str, true);
。如果我将其注释掉并将硬编码值添加到我的 search_suggest div 中,则该功能可以正常工作。这个 php 页面只是在后面用换行符回显值。
我在 html 页面上的输入是
<form id="frmSearch" action="/search/index.php" method="get">
<input type="text" id="zoom_query" name="zoom_query" alt="Search Criteria" onkeyup="searchSuggest(); " autocomplete="off" />
<input type="image" src="/images/search_button.gif" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" /><br/>
<div id="search_suggest">
</div>
</form>
在我的 js 页面上,我有
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser is out of date");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = escape(document.getElementById('zoom_query').value);
searchReq.open("GET", '/search/ajax-suggest.php?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
var suggest = '<div class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
}
$(document).keyup(function(e) {
var $hlight = $('div.suggest_link_over'), $div = $('div.suggest_link');
if (e.keyCode == 40) {
$hlight.removeClass('suggest_link_over').next().addClass('suggest_link_over');
if ($hlight.next().length == 0) {
$div.eq(0).addClass('suggest_link_over')
}
} else if (e.keyCode === 38) {
$hlight.removeClass('suggest_link_over').prev().addClass('suggest_link_over');
if ($hlight.prev().length == 0) {
$div.eq(-1).addClass('suggest_link_over')
}
}
})