2

我有两个同时发生的主干模型更改事件:

  1. change:path替换当前历史状态并修补页面上的一些链接,
  2. change:language应该使用额外的哈希重定向到新路径

重定向应该取代替换状态,但如果提供了散列,则不会发生这种情况。我正在尝试让它在 Chrome 中工作。

此代码不会重定向:

// in change:path event
window.history.replaceState({state: 1}, "", "/new_path");

// in change:language event
window.location.replace("/new_path#hash");

但是没有哈希它可以按预期工作:

// in change:path event
window.history.replaceState({state: 1}, "", "/new_path");

// in change:language event
window.location.replace("/new_path");

有没有办法让它与哈希一起工作?我知道我可以添加一些时间戳来使新 url 完全不同,但我希望 url 是干净的。

4

2 回答 2

1

我设法以一种不太干净的方式解决了它,但我仍在寻找更好的解决方案:

// change:path event
window.history.replaceState({state: 1}, "", "/new_path");

// change:language event
setTimeout(function(){
  // make sure it runs after replaceState in change:path
  window.history.replaceState({}, "", "/"); 
  window.location.replace("/new_path#hash");
}, 10);
于 2012-10-31T15:05:45.263 回答
1

看起来最好的方法是不使用该replace方法,而只是将位置设置为一个整体。像这样:

window.location.href = 'http://www.sitename.com/new_path#hash';
于 2012-10-31T15:06:48.280 回答