Html replaceState() 与 pushState()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17507091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replaceState() vs pushState()
提问by Rikard
I've been reading and searching for advantages / disadvantages between replaceState()
& pushState()
.
Read also Mozilla's article, and this interestingtest but still is unclear to me the differences.
我一直在阅读和寻找replaceState()
&之间的优点/缺点pushState()
。另请阅读 Mozilla 的文章和这个有趣的测试,但我仍然不清楚它们之间的差异。
Any one care to explain in what they differ?
有人愿意解释它们的不同之处吗?
回答by
replaceState()
will changethe URL in the browser (ie. pressing the back button won't take you back)
replaceState()
将更改浏览器中的 URL(即,按后退按钮不会让您返回)
pushState()
will change the URL, and keep the old one in the browser history (ie. pressing the back button will take you back)
pushState()
将更改 URL,并将旧的保留在浏览器历史记录中(即按后退按钮将带您返回)
回答by keyboardP
From your link
从你的链接
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.
replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
history.replaceState() 的操作与 history.pushState() 完全一样,除了 replaceState() 修改当前历史条目而不是创建新历史条目。
当您想要更新当前历史条目的状态对象或 URL 以响应某些用户操作时,replaceState() 特别有用。
If you want simply want to update history entry, use replaceState()
otherwise use pushState()
, which will keep the old entry and create a new one. They're similar but both have different effects so it depends on whether or not you want to replace or create new history entries.
如果您只想更新历史条目,请使用replaceState()
否则使用pushState()
,这将保留旧条目并创建一个新条目。它们很相似,但都有不同的效果,因此这取决于您是否要替换或创建新的历史记录条目。
Think of it like I'm dealing out a deck of cards by putting one card on top of the other (face up) and you can only take the top card in the pile (i.e. the last card I dealt). Let's say I put a Hyman of Hearts on the pile. Now for the next card if I use replaceState
, so I take that Hyman of Hearts off and put the next card on. The number of cards is the same since we just replaced the top card. If I had used pushState
instead, I would've put the next card on top of the Hyman of Hearts (so now both exist in the pile and the pile is one card higher).
把它想象成我正在发一副牌,把一张牌放在另一张上面(面朝上),你只能拿到堆中最上面的一张牌(即我发的最后一张牌)。假设我在纸堆上放了一个红心Hyman。现在换下一张牌,如果我使用replaceState
,所以我把那张红心Hyman取下并放上下一张牌。卡的数量是相同的,因为我们刚刚更换了最上面的卡。如果我pushState
改用,我会把下一张牌放在红心Hyman的上面(所以现在这两张牌都在堆中并且堆高一张牌)。
Swap the cards in the analogy with URLs and that's how the URL history is modified.
用 URL 类比交换卡片,这就是修改 URL 历史的方式。