【问题标题】:Browser back button with divs hidden with css用css隐藏div的浏览器后退按钮
【发布时间】:2018-03-26 07:29:37
【问题描述】:

我有一个网站,其中显示房地产搜索结果就像使用 <div>s 一样,默认情况下只显示 6 个和“加载更多”按钮。当用户点击加载更多按钮时,显示更多帖子等。如何完成:divs 默认隐藏(display: none;),然后将.show 类添加到接下来的 9 个项目中。

a("span.more-search-items").on("click", function(t) {
    t.preventDefault();
    var e = a(this).parents(".property-search");
    e.find(".prop").not(".show").slice(0, 9).each(function() {
        var t = a(this).attr("data-img");
        a(this).css("background-image", "url(" + t + ")"), a(this).find(".main-image").attr("src", t), a(this).addClass("show")
    }), 0 == e.find(".prop").not(".show").length && a("span.more-search-items").hide();
    e.find(".prop.show").length

当用户转到单个属性然后点击返回浏览器按钮时,它会再次显示前 6 个项目。我尝试在那里实现history.pushState() 方法,其中每个“加载更多”按钮单击的 URL 都会发生变化:

var href = window.location.href.replace(window.location.hash, '');
var currentPage = location.hash.replace("#","");
history.pushState(null, null, href + "#" + (+currentPage + 1));

网址发生了变化,但故事仍然相同 - 当用户返回历史记录时,仅显示前 6 个结果。在这种情况下我能做些什么吗?

【问题讨论】:

  • 所以你加载所有的 div 并使用 Load more 来显示它们?
  • 是的,然后只延迟加载图像。

标签: javascript jquery browser-history


【解决方案1】:

如果你需要处理History API你需要

  • 在加载更多点击时,您需要推送或替换历史记录,例如带有哈希 #15 , #24 的可见 div 的数量@ 类似这样的内容

  • 在推送/替换状态下,您需要使用$(window).on('popstate' , function(){ alert(window.location.hash); }),当用户转到单个属性时,它会刷新所有页面,当点击浏览器后退按钮时,它会返回并刷新上一页..所以你需要在页面加载时检查alert(window.location.hash);

最后,当您收到来自window.location.hash 号码的警报时,您可以根据它显示 div

好的,让我用代码为你解释一下

$(document).ready(function(){

    alert(window.location.hash); // check the alert here

    $('.load_more_button').on('click' , function(){
        if(window.location.hash){
           var href = window.location.href.split('#');
           var currentPage = parseInt(window.location.hash);
           history.pushState(null, null, href[0] + "#" + (+currentPage + 1));
        }
    });
    $(window).on('popstate' , function(){
        alert(window.location.hash);  // check the alert here
    });
});

拿到号码后就可以从这里开始做你喜欢的事情

【讨论】:

  • 感谢您的方法,它奏效了。最后我没有使用popstate,而是计算(".prop.show").length,相应地用history.pushState更新URL中的哈希,然后根据窗口加载的哈希将CSS类添加到帖子中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 2013-09-03
  • 2011-08-06
  • 2011-02-17
  • 1970-01-01
相关资源
最近更新 更多