js 实现超链接
使用 HTML 的 <a> 标签
在 JavaScript 中动态创建超链接可以通过操作 DOM 实现。通过 document.createElement 创建一个 <a> 元素,设置其 href 和 textContent 属性,然后将其添加到 DOM 中。
const link = document.createElement('a');
link.href = 'https://example.com';
link.textContent = '点击访问示例网站';
document.body.appendChild(link);
使用 innerHTML 或 insertAdjacentHTML
通过 innerHTML 或 insertAdjacentHTML 直接插入 HTML 字符串也是一种快速实现超链接的方式。
document.body.innerHTML += '<a href="https://example.com">点击访问示例网站</a>';
document.body.insertAdjacentHTML('beforeend', '<a href="https://example.com">点击访问示例网站</a>');
使用 window.location 实现页面跳转
如果需要通过 JavaScript 直接跳转到另一个页面,可以使用 window.location.href。
window.location.href = 'https://example.com';
动态生成多个超链接
结合数组和循环,可以批量生成多个超链接。
const links = [
{ url: 'https://example.com', text: '示例网站' },
{ url: 'https://google.com', text: 'Google' }
];
links.forEach(linkData => {
const link = document.createElement('a');
link.href = linkData.url;
link.textContent = linkData.text;
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
});
添加事件监听器
为超链接添加点击事件监听器,可以在跳转前执行自定义逻辑。
const link = document.createElement('a');
link.href = '#';
link.textContent = '点击我';
link.addEventListener('click', (event) => {
event.preventDefault();
alert('即将跳转');
window.location.href = 'https://example.com';
});
document.body.appendChild(link);
使用 target 属性控制打开方式
通过设置 target 属性,可以控制链接是在当前页面打开还是在新标签页打开。
const link = document.createElement('a');
link.href = 'https://example.com';
link.textContent = '在新标签页打开';
link.target = '_blank';
document.body.appendChild(link);






