在 JavaScript 中单击 Button 在新选项卡中打开链接
要在按钮上的新选项卡中打开链接,请单击:
- 选择按钮元素。
- 向按钮添加事件侦听器。
-
使用
window.open()
方法在新选项卡中打开链接。 -
例如,
window.open('https://example.com', '_blank')
。
这是我们的 index.html 文件的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button onclick="window.open('https://google.com', '_blank')">
Open Google in new tab
</button>
<button id="example-btn">Open Example in new tab</button>
<script src="index.js"></script>
</body>
</html>
文件中的第一个按钮有一个内联点击处理程序,第二个按钮只有一个 id 属性集。
这是我们的 index.js 文件。
const exampleBtn = document.getElementById('example-btn');
exampleBtn.addEventListener('click', () => {
window.open('https://example.com', '_blank');
});
我们使用 document.getElementById
方法来选择按钮元素。
每次单击按钮时,我们传递给 addEventListener
方法的函数都会被调用。
在我看来,定义一个单独的点击处理程序是一种更简洁的方法。
index.html 文件中的第一个按钮使用内联点击处理程序,但是,与在具有
.js
扩展名的文件中编写代码相比,通过内联事件处理程序获得 IDE 支持要困难得多。
window.open
方法将指定的 URL 加载到新的或现有的浏览上下文中。
我们传递给该方法的第一个参数是 URL 字符串。
确保在 URL 前加上协议前缀,例如 https://
如果我们链接到外部资源。
window.open()
方法采用的第二个参数是目标 - 一个指定浏览上下文名称的字符串。
通过将目标设置为 _blank
,我们在新选项卡中打开资源。
从技术上讲,当目标设置为
_blank
时,用户可以将他们的浏览器配置为在新窗口(而不是选项卡)中打开资源,但这种情况很少见。 另一个常用的目标选项是_self
- 它在当前浏览上下文中打开 URL。
我们可以在 MDN 文档的这一部分查看所有可能的目标选项。
我们可能还看到 target 被设置为带有锚点 <a>
元素的 _blank
。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button onclick="window.open('https://www.jiyik.com', '_blank')">
Open 迹忆客 in new tab
</button>
<button id="example-btn">Open Example in new tab</button>
<!-- 👇️ 也可以在锚元素上设置 target _blank -->
<a href="https://www.jiyik.com" target="_blank">迹忆客</a>
<script src="index.js"></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
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。