js 实现超链接
使用HTML的<a>标签
在HTML中直接使用<a>标签创建超链接,href属性指定目标URL,target属性控制打开方式(如_blank在新标签页打开)。

<a href="https://example.com" target="_blank">点击跳转</a>
通过JavaScript动态创建
使用document.createElement动态生成<a>元素,并设置属性后插入DOM:

const link = document.createElement('a');
link.href = 'https://example.com';
link.textContent = '动态链接';
document.body.appendChild(link);
修改现有元素的点击事件
通过事件监听实现超链接行为,适合需要条件判断的场景:
document.getElementById('myElement').addEventListener('click', () => {
window.location.href = 'https://example.com'; // 当前页跳转
// 或 window.open('https://example.com', '_blank'); // 新标签页
});
使用location对象跳转
直接通过window.location实现页面跳转:
window.location.assign('https://example.com'); // 可回退
window.location.replace('https://example.com'); // 不可回退
注意事项
- 动态创建的链接需确保DOM已加载(如放在
DOMContentLoaded事件中)。 window.open可能被浏览器拦截,需用户主动触发(如点击事件)。- 使用
target="_blank"时建议添加rel="noopener noreferrer"增强安全性。






