我参加了一个视频,介绍了如何在输入中实现自动完成功能。最后我在firefox和chrome中进行了测试,除了在Internet Explorer中之外它运行良好:这里是下面的代码:
jquery:
function getSuggestions(value){
if(value!=''){
$.get('suggest.php', {requestKword:value}, function (data){
$('#suggestions').show();
$('#suggestions').html(data);
doCSS();
});
}
else{
removeSuggestions();
}
}
function removeSuggestions(){
$("#suggestions").html("");
undoCSS();
}
function fill(thisValue) {
$('#ii').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
function doCSS(){
$("#suggestions").css({
'border' : 'solid',
'border-width':'1px',
'position': 'relative'
});
}
function undoCSS(){
$("#suggestions").css({
'border' : '',
'border-width':''
});
}
function addText(value){
$("#ii").val(value);
}
css:
#suggestions{
text-align:left;
padding-left:5px;
font-size:14px;
}
#link:hover{ background-color:#f0f0f0; cursor:default;}
html:
<form action="/" method="get" id="set" name="set">
<input id="ii" type="text" name="q" size="96px" value="" onblur="fill();" onkeyup="getSuggestions(this.value)" /><br />
<div id="suggestions"></div>
</form>
mysql: suggest.php
mysql_connect('localhost', 'root', '');
mysql_select_db('keywords') or die (mysql_error());
$keyword=mysql_real_escape_string($_GET['requestKword']);
$result = mysql_query("SELECT * FROM `table`.`keys` where `column` like '$keyword%' LIMIT 0 , 10") or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
echo '<div id="link" onclick="addText(\''.$row['keyword'].'\')" ">'.$row['keyword'].'</div>';
}
答案 0 :(得分:0)
请查看这是否适合您...
将这些行添加到jQuery代码中:
$("#ii").keyup(function() {
getSuggestions(this.value);
});
$("#ii").blur(function(){
fill();
});
替换以下HTML行:
<input id="ii" type="text" name="q" size="96px" value="" onblur="fill();" onkeyup="getSuggestions(this.value)" /><br />
使用:
<input id="ii" type="text" name="q" size="96px" value="" /><br />
答案 1 :(得分:0)
您可能需要在此处考虑jQuery自动完成插件:http://jqueryui.com/autocomplete/。它有很好的工作演示;提示......
答案 2 :(得分:0)
最后我找到了解决方案,非常简单:
我在php代码中添加了一些代码:
之前:
mysql_connect('localhost', 'root', '');
mysql_select_db('keywords') or die (mysql_error());
$keyword=mysql_real_escape_string($_GET['requestKword']);
$result = mysql_query("SELECT * FROM `table`.`keys` where `column` like '$keyword%' LIMIT 0 , 10") or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
echo '<div id="link" onclick="addText(\''.$row['keyword'].'\')" ">'.$row['keyword'].'</div>';
}
之后:
mysql_connect('localhost', 'root', '');
mysql_select_db('keywords') or die (mysql_error());
$keyword=mysql_real_escape_string($_GET['requestKword']);
$result = mysql_query("SELECT * FROM `table`.`keys` where `column` like '$keyword%' LIMIT 0 , 10") or die (mysql_error());
if($result)
{
while($row = mysql_fetch_assoc($result)){
echo '<div id="link" onclick="addText(\''.$row['keyword'].'\')" ">'.$row['keyword'].'</div>';
}
}