我有一个用jQuery编写的Google Instant样式搜索脚本,它从PHP脚本中提取结果。当用户查询某些内容时,他们的查询会在页面标题中显示为“ QUERY - 我的搜索脚本”,并在页面的网址中显示为< QUERY 。但是,当您从搜索框中删除所有文字时,#仍保留在网址中,标题显示为“ - 我的搜索脚本”。如何清除所有搜索框内容,脚本删除了标题和#?
我的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=query;
document.title=$(this).val()+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
});
答案 0 :(得分:1)
您可以很容易地整理<title>
,但是一旦设置了哈希,您将无法从URL中一致地删除#
。似乎摆脱它的唯一浏览器是Firefox。
$(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=query;
// You may want to use a better title than '\xa0' (blank)
document.title = search=='' ? '\xa0' : search+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
});
答案 1 :(得分:1)
这样的事情怎么样:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&category=web';
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
if (query == "") {
window.location.hash=query;
document.title=$(this).val()+" - My Search Script";
} else {
window.location.hash=query;
document.title="My Search Script";
}
}
});
});
});
我所做的改变是:
答案 2 :(得分:-1)
试试这个:
$(document).ready(function() {
$('#search').keyup(function() {
var search = $(this).val();
if(search == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#result').empty();
}
else {
window.location.hash = encodeURIComponent(search);
document.title = search + ' - My Search Script';
$.ajax({
type: 'GET',
url: 'search.php',
data: {q: search, category: 'web'},
dataType: 'html',
success: function(response){
$('#result').html(response);
}
});
}
});
});
我使用了data
的{{1}}选项,因此您无需自行构建网址。
我认为你不能保证摆脱网址中的哈希值:有些浏览器删除它,有些浏览器不删除它。