JavaScript 使用 a 标签打开网址 - 完整指南
在 JavaScript 中,可以使用 window.open() 方法来打开一个新的浏览器窗口,并指定要打开的网址。例如:
function openWebsite(url) {
window.open(url);
}
// 调用函数打开网址
openWebsite("https://www.example.com");
另外,如果要通过点击 <a> 标签来打开网址,可以结合使用 window.location.href 属性。例如:
<a href="https://www.example.com" target="_blank" onclick="openWebsite(event)">打开网址</a>
<script>
function openWebsite(event) {
event.preventDefault(); // 阻止默认的链接跳转行为
var url = event.target.href;
window.open(url);
}
</script>
这样,当点击链接时,会先执行 openWebsite() 函数来打开网址,并阻止默认的链接跳转行为。
原文地址: https://www.cveoy.top/t/topic/p1Vm 著作权归作者所有。请勿转载和采集!