I have a Google Instant style search script written in jQuery which pulls results from a PHP script. When a user queries something, their query is displayed in the title of the page as "QUERY - My Search Script" and in the url of the page as #QUERY. However, when you delete all the text from the search box the # still stays in the url and the title says " - My Search Script". How can I make it so when all of the search box content is cleared, the script removed the title and the #?开发者_高级运维
My jQuery code is:
$(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);
}
});
});
});
You can tidy the <title>
up easy enough but you won't be able to consistently remove the #
from the URL once you've set a hash. The only browser that seems to get rid of it is 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);
}
});
});
});
How about something like this:
$(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";
}
}
});
});
});
The changes I made are:
- Don't update the title and hash until the new data is loaded.
- Behave differently if the searched for query is an empty string.
Try this:
$(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);
}
});
}
});
});
I've used the data
option of $.ajax
so that you don't need to build the url yourself.
I don't think you can guarantee to get rid of the hash in the URL: Some browsers remove it, others don't.
精彩评论