在 JavaScript 中使用 Onclick 转到 URL
window 对象是用于与浏览器对话的最重要的对象之一。它代表浏览器的窗口。所有的全局变量、函数都成为 window 对象的成员。窗口的位置对象用于获取当前页面的 URL 以及更改重定向的 URL。
在今天的文章中,我们将学习如何在 JavaScript 中使用 onclick
访问 URL。
JavaScript window 对象提供了两种方式,第一种是使用 location 属性,第二种是使用 open()
方法。
在 JavaScript 中使用 window.open()
转到 URL
它是 JavaScript 提供的一种 Window 接口方法,它将指定的 URL/资源加载到具有指定名称的新标签页或现有浏览器中。此方法将生成一个用于打开指定 URL 的新窗口。每次 window.open()
方法返回它都包含 about:blank
。当前脚本块完成执行后,将加载实际 URL。
JavaScript 中 window.open()
的语法
window.open(url, windowName, windowFeatures);
参数
url
:这是一个强制参数,它接受有效的 URL、图像路径或浏览器支持的其他资源。如果传递空字符串,它将打开一个带有空白 URL 的新标签页。windowName
:它是一个可选参数,它指定浏览上下文的名称。这不定义窗口的标题。此外,此窗口名称不应包含任何空格。windowFeatures
:这是一个可选参数。此参数接受新标签页的逗号分隔窗口属性,形式为name=value
,如果属性是布尔值,则仅接受name
。一些特性是窗口对象的默认位置和大小。
示例代码:
<button type="button" id="btn" onclick="openGoogleByMethod()">Open Google</button>
window.open('https://www.google.com');
在 JavaScript 中使用 window.location
转到 URL
它是 window.location
的只读属性,返回 Location
对象。此对象包含有关文档当前位置的信息。位置对象还包含其他属性,如 href
、protocol
、host
、hostname
、port
等。
window.location
的属性也可以使用 location
直接访问,因为 window 对象始终保留在作用域链的顶部。用户可以使用 href
属性或 assign
Location 对象的方法来加载/打开其他 URL/资源。
语法
window.location = URL_PATH;
window.location.href = URL_PATH;
window.location.assign(URL_PATH);
参数
URL_PATH
:这是一个强制参数,接受需要打开的有效 URL。此 URL 可以是绝对 URL、相对 URL、锚 URL 或新协议。
示例代码:
<button type="button" id="btn" onclick="openGoogle()">Open Google</button>
window.location = 'https://www.google.com';
window.location.href = 'https://www.google.com';
相关文章
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 事件。