在 JavaScript 中的同一窗口或标签页中打开 URL
我们将在本文中了解如何在同一窗口或标签页中打开 URL。
在 JavaScript 中使用 window.open()
方法的同一窗口或标签页中打开 URL
window.open()
方法是一种 JavaScript 预定义的窗口技术,用于在浏览器的同一窗口和标签页中打开新标签页或窗口。
根据你的浏览器设置或 window.open()
方法中提供的参数,将打开一个新窗口或标签页。
语法:
window.open(url, '_self');
如果传递此选项,则 URL 将替换先前输出的 _self
值和一个新窗口将出现在同一框架中。
例子:
使用 .html
扩展名保存代码并运行以下脚本。
<html>
<body>
<form id="formA" runat="server">
<div style="text-align:center; font: size 25px;">
<label>Welcome to same page redirect</label><br><br>
<input type="button" value="Google.Com" class="btn" id="btnn">
</div>
</form>
<script type="text/javascript">
document.getElementById("btnn").addEventListener("click", (e) =>{
let url ="https://www.google.com/";
window.open(url, "_self");
})
</script
</body>
</html>
输出:
在点击按钮之前:
单击该按钮后,它将在同一窗口的同一标签页中打开一个新 URL。
在 JavaScript 中使用 location.replace()
方法的同一窗口或标签页中打开 URL
replace()
方法用 JavaScript 中的另一个页面替换当前页面。replace()
方法将当前窗口的 URL 更改为 replace()
方法中指定的 URL。
语法:
location.replace(URL);
此函数仅接受单个 URL 参数。该 URL 链接到必须替换为较早版本的另一个页面。
此方法在同一框架中返回或打开一个带有新页面 URL 的新窗口。
例子:
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to same page redirect to different url</h1>
<h2>The replace Property</h2>
<button onclick="Function()">Replace document</button>
<script>
function Function() {
location.replace("https://www.google.com")
}
</script>
</body>
</html>
在点击按钮之前:
点击按钮后:
相关文章
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 事件。