我可以阻止history.popstate在初始页面加载时触发吗?

时间:2011-03-06 10:47:27

标签: javascript jquery history getscript popstate

我正在开发一个通过AJAX提供内容的网站。

如果您点击菜单中的某个项目,内容div会更新$.get响应,没什么特别的。

我正在实施history.pushState以允许使用浏览器的后退/前进按钮进行导航。

我有以下内容在历史导航中加载内容:

$(function() {
    $(window).bind("popstate", function() {
        $.getScript(location.href); 
    });
});

问题是,当第一次加载页面时,此函数执行$.getScript,因此页面会立即再次加载。第一次加载页面时,它会呈现初始HTML视图,然后在第二次加载时呈现JS视图,因为它是一个JS请求。

如何阻止此事件在包含HTML请求的网页上触发?

5 个答案:

答案 0 :(得分:37)

使用原生HTML5历史记录API会遇到一些问题,每个HTML5浏览器都会稍微处理不同的API,因此您不能只编写一次代码并期望它能够在不实施变通方法的情况下工作。 History.js为HTML5历史记录API提供跨浏览器API,并为HTML4浏览器提供可选的hashchange备用,如果您想沿着这条路线前进的话。

要将您的网站升级为RIA / Ajax-Application,您可以使用以下代码段: https://github.com/browserstate/ajaxify

这是较长篇文章Intelligent State Handling的一部分,其中涉及hashbang,哈希和html5历史api的解释。

如果您需要任何进一步的帮助,请告诉我:)干杯。

答案 1 :(得分:23)

您需要获取event.originalEvent

// Somewhere in your previous code
if (history && history.pushState) {
  history.pushState({module:"leave"}, document.title, this.href);
}


$(window).bind("popstate", function(evt) {
  var state = evt.originalEvent.state;
  if (state && state.module === "leave") {
    $.getScript(location.href);
  }
});

答案 2 :(得分:8)

当在页面加载时触发popstate事件时,它不会在事件对象中具有state属性。这允许您检查是否针对页面加载触发了事件。

window.onpopstate = function (event) {
  if (event.state) {
    // do your thing
  } else {
    // triggered by a page load
  }
}

答案 3 :(得分:4)

首次加载浏览器时,它始终会触发一个popstate事件。所以你需要确定这个popstate是否属于你。

执行pushState时,请确保拥有状态对象。这样你以后可以查看。

然后在popstate处理程序中,检查状态对象:)

$(function() {
    $(window).bind("popstate", function(data) {
        if (data.state.isMine)
            $.getScript(location.href); 
    });
});

// then add the state object
history.pushState({isMine:true},title,url);

如果您需要更多帮助,请告诉我们。)

答案 4 :(得分:0)

我用它来更改条形地址并保存当前状态,包括当前的html正文,然后我重新加载它在后面的bouton点击而没有任何其他的ajax调用。全部保存在您的浏览器中:

  1. $(document).ajaxComplete(function(ev, jqXHR, settings) {
    
        var stateObj = { url: settings.url, innerhtml: document.body.innerHTML };
        window.history.pushState(stateObj, settings.url, settings.url);
    });
    
    
    window.onpopstate = function (event) {
        var currentState = history.state;
        document.body.innerHTML = currentState.innerhtml;
    };
    
相关问题