JavaScript 中修改 URL
浏览器的历史界面控制浏览器的会话历史。它包含在显示当前页面的标签页或框架中访问的最后一页。
操纵此状态允许你在不重新加载页面的情况下更改浏览器的 URL。在本文中,我们将使用 JavaScript 中的不同方法处理修改 URL。
replaceState()
方法通过将状态的属性替换为提供的参数中的属性来替换历史中的当前状态。
语法:
history.replaceState(data, title ,url)
数据代表浏览器历史的当前状态,标题指的是新页面的标题,URL 指的是新标题页面的 URL。
例子:
<!DOCTYPE html>
<html>
<head>
<title>
modify URL
</title>
</head>
<body>
<b>
Modify URL without reloading the page
</b>
<p>
To change the current status of the history, click the button below.
</p>
<button onclick="modifyState()">
Modify history state
</button>
<script>
function modifyState() {
let stateObj = { id: "100" };
window.history.replaceState(stateObj, "x 2", "/x2.html");
}
</script>
</body>
</html>
这种方法不是产生一个新的历史项目,而是更新当前的。当我们希望更新当前历史记录的 URL 时,我们使用此方法。
可以通过将所需的 URL 作为字符串提供给此方法来更改 URL。这将修改页面的 URL,而无需重新加载。
输出:
在点击按钮之前:
点击按钮后:
作为 pushState()
方法的输入的属性会创建一个新的历史记录条目。在不重新启动页面的情况下,这会将当前 URL 更新为指定的新状态。
语法:
history.pushState(state object, title, url)
例子:
<!DOCTYPE html>
<html>
<head>
<title>
Modify URL
</title>
</head>
<body>
<b>
modify URL without reloading
the page
</b>
<p>
To change the current status of the history, click the button below.
</p>
<button onclick="addState()">
Add history state
</button>
<script>
function addState() {
let stateObj = { id: "100" };
window.history.pushState(stateObj,
"x 2", "/x2.html");
}
</script>
</body>
</html>
可以通过将所需的 URL 作为字符串提供给此方法来更改 URL。这将修改页面的 URL,而无需重新加载。
输出:
在点击按钮之前:
点击按钮后:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。