我遵循W3Schools教程進行AJAX實時搜索,並且它一直在正常工作。我將我的AJAX結果作爲錨點元素返回。Ajax下拉鍵盤導航(上和下箭頭)
我想爲Ajax下拉菜單添加鍵盤導航(即向上箭頭和向下箭頭),而我最好的結果是將焦點放在僅停留一秒鐘然後焦點消失的第一個結果上。我想知道爲什麼這個焦點消失了,以及以任何方式避開它。
我的JavaScript代碼:
<script type="text/javascript">
$(document).ready(function(){
$('#searchInput').keyup(function(e){
var keyCode = e.keyCode || e.which;
if (keyCode == 40){
$('.hint').first().focus();
$('.hint').first().css('color','#E8AE00'); //I can get the focus to here, but the focus will disappear right away.
}
})
})
</script>
這是我的PHP代碼:
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc -> load("database.xml");
$rest = $xmlDoc -> getElementsByTagName('restaurant');
if (strlen($q)>0){
$hint[] = "";
$index = 0;
for ($i = 0; $i < ($rest->length); $i++){
$name = $rest -> item($i) -> getElementsByTagName('name');
$link = $rest -> item($i) -> getElementsByTagName('link');
if ($name -> item(0) -> nodeType == 1){
if (strtolower($q) == strtolower(substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,0,strlen($q)))){ //if matching
$hint[$index] = "<a class='hint' id='hint".$index."' href='".$link -> item(0) -> childNodes -> item(0) -> nodeValue."' onfocus=\"this.style.color='#E8AE00'\">".substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,0,strlen($q))."<b>".substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,strlen($q))."</b></a><br />";
$index++;
}
}
}
}
if ($hint[0] == ""){
echo "no suggestion";
}
else {
for ($j = 0; $j < (count($hint)); $j++){
echo $hint[$j];
}
}
?>
感謝。
你有沒有其他方法運行後的密碼?聽起來好像另一個事件監聽器或延遲的方法正在關注你的焦點。 – AMember