我有来自数据库的自动完成搜索代码。这里正在进行搜索,因为我正在键入字母,相关的名称就像Google一样从数据库中显示。
问题在于此搜索结果我无法使用箭头键进行选择。请帮助我添加任何代码。
谢谢!
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
<script type="text/javascript">
function hint(string)
{
if(string.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if(window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get.php?searchid="+string,true);
xmlhttp.send();
}
</script>
<style type="text/css">
body{
font-family:Tahoma, Geneva, sans-serif;
font-size:18px;
}
.content{
width:900px;
margin:0 auto;
padding:0px;
}
#searchid
{
width:500px;
border:solid 1px #000;
padding:10px;
font-size:14px;
}
#result
{
position:relative;
width:500px;
padding:10px;
display:none;
margin-top:-1px;
border-top:0px;
overflow:hidden;
border:1px #CCC solid;
background-color: white;
}
.show
{
padding:10px;
font-size:15px;
height:10px;
}
.show:hover
{
background:#4c66a4;
color:#FFF;
cursor:pointer;
}
</style>
</head>
<body>
<form method="GET" onkeyup="hint(this.value)">
<div class="content">
<p><font face="cambria" color="green" size="6"><b>Search Staff byName</b>
<input type="text"class="search" onkeyup="hint(this.value)id="searchid">
<div id="result" align="center">
</div>
</div>
答案 0 :(得分:0)
您可以在此处使用向上和向下箭头自动填充,试试这个以获得答案。
$(document).on('keyup keydown', '.search', function(){
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});