2011-06-09 39 views
0

我有用jQuery编写的Google即时样式搜索脚本。当用户搜索时,会创建一个类似#search/QUERY/3 /的URL。但是,当您重新加载页面时,单击转到其他页面的结果或从前一页面返回时搜索结果不再存在。为什么会这样呢?在页面重新载入后加载动态生成的内容和URL

这里是我的jQuery代码:

$(document).ready(function(){ 
    $("#search").keyup(function(){ 
     var search=$(this).val(); 
     var query=encodeURIComponent(search); 
     var page=1; 
     var yt_url='search.php?q='+query+'&category=web&d='+page+''; 
     window.location.hash='search/'+query+'/'+page+'/'; 
     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("Your search did not return any results"); 
       } 
      } 
     }); 
    }); 
if(window.location.hash.indexOf('#search/')==0){ 
    query=window.location.hash.replace('#search/', '').replace('/1/', ''); 
    $('#search').val(decodeURIComponent(query)).keyup(); 
} 
}); 

我认为这可能是一些做的这行代码:

if(window.location.hash.indexOf('#search/')==0){ 
    query=window.location.hash.replace('#search/', '').replace('/1/', ''); 
    $('#search').val(decodeURIComponent(query)).keyup(); 
} 
+0

我用JavaScript代码创建了一个带有文本框和结果div的页面,它在Firefox和Chrome上按预期工作。也许别的东西会覆盖你的内容,或者你正在绑定/从文本框中删除事件。 – guzart 2011-06-09 21:14:09

+0

但你有没有尝试删除除了你粘贴在这里的一切?尽可能简单。 – guzart 2011-06-09 21:38:47

+0

这工作? http://kisurfer.com/test.html – guzart 2011-06-09 21:46:24

回答

0

你需要写一个函数的搜索,所以你可以指定页码。

$(document).ready(function(){ 
    var search = function (query, page) { 
    page = page ? page : 1; 
    query = encodeURIComponent(query), 
    var yt_url = 'search.php?q=' + query + '&category=web&d=' + page + ''; 
    if (query == '') { 
     window.location.hash = ''; 
     document.title = 'My Search Script'; 
    } else { 
     window.location.hash = 'search/' + query + '/' + page + '/'; 
     document.title = $(this).val() + " - My Search Script"; 
    } 
    $.ajax({ ... }); 
    }; 

    $("#search").keyup(function(){ search(this.value); }); 

    if (window.location.hash.indexOf('#search/') == 0) { 
    var query = window.location.hash.replace('#search/', ''), 
     page = query.replace(/.+?\/(\d+)\//, '$1'); 
    query = query.replace(/\/\d+\//, ''); 
    search(decodeURIComponent(query), page); 
    } 
}); 
相关问题