仅在使用jQuery的搜索框中显示文本
问题描述:
我有一个用jQuery编写的Google即搜样式搜索脚本,它查询PHP文件。目前,当没有找到结果时,PHP文件不会返回任何HTML代码,因此脚本会显示一条消息,提示“未找到结果”。但是,如果搜索框中没有搜索条件,并且查询字符串为空,则仍会显示此消息。我怎样才能得到它,以便只有在搜索框中有文字时才显示消息?仅在使用jQuery的搜索框中显示文本
这里是我的jQuery代码:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&category=web';
window.location.hash='search/'+query+'/1/';
document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
} else {
$("#result").html("No results were found.");
}
}
});
});
});
答
请求仍然是射击,即使是没有在搜索领域。只有在字段不为空时才发出请求。
当用空字符串进行搜索时,“search”的值是多少?为什么你的'if(search ='')'测试没有捕获它? – Dexter 2011-06-05 22:01:48