【问题标题】:Loading dynamic div content with jQuery from a URL使用 jQuery 从 URL 加载动态 div 内容
【发布时间】:2011-07-17 01:52:38
【问题描述】:

我有一个 jQuery 搜索脚本,它使用选项卡让用户定义他们想要使用的搜索类型。当用户搜索时,会创建一个类似于 #type/query/ 的 URL。但是,当您重新加载页面时,单击转到不同页面的结果或从前一页面返回时,搜索结果不再存在。为什么会这样,我该如何解决这个问题?我也不想用任何插件。

我的 jQuery 代码是:

$(document).ready(function () {
    $('[id^=type_]').click(function () {
        type = this.id.replace('type_', '');
        $('[id^=type_]').removeClass('selected');
        $('#type_' + type).addClass('selected');
        return false;
    });
    $('#type_search').click();
    $('#query').keyup(function () {
        var query = $(this).val();
        var url = '/' + type + '/' + query + '/';
        window.location.hash = '' + type + '/' + query + '/';
        document.title = $(this).val() + ' - My Search';
        $('#results').show();
        if (query == '') {
            window.location.hash = '';
            document.title = 'My Search';
            $('#results').hide();
        }
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            success: function (results) {
                $('#results').html(results);
            }
        });
    });
    var textlength = $('#query').val().length;
    if (textlength <= 0) {
        $('#query').focus();
    } else {
        $('#query').blur();
    }
});

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    当您重新加载页面时,结果丢失的原因是因为它们不在文档源中;它们后来被添加到 DOM 中。

    我认为你有两个选择,我通常使用第一个。

    当您执行搜索时,将搜索条件或搜索结果存储在服务器上,以便在下一次呈现页面时,与它一起呈现结果。我使用 ASP.NET MVC 3 并使用 PartialView 执行此操作。当我使用 jQuery 执行搜索时,它会导致服务器呈现相同的 PartialView 并将生成的 HTML 片段插入到结果 div 中。

    或者,您需要在重新加载页面时再次触发 jQuery 搜索。

    是重新提交搜索还是缓存结果更好取决于搜索的成本以及结果集可能有多大。

    【讨论】:

      【解决方案2】:

      哈希应该在页面重新加载后保留,因为它是浏览器历史记录的一部分。 因此,您可以解析document.location.hash 以获取有关所选查询类型和搜索的知识。

      //$(function() {
          if(document.location.hash) {
              var hash = document.location.hash;
              var split = hash.split('/');
              var queryType = hash[1];
              var searchTerm = hash[2];
              $('#type_'+queryType).addClass('selected');
              $('#query').text(searchTerm);
              $('#query').keyup();
          }
      //});
      

      在您的设置例程背后。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 1970-01-01
        • 2011-06-14
        • 2010-10-30
        • 1970-01-01
        • 2012-06-06
        相关资源
        最近更新 更多