js实现点击跳转
实现点击跳转的JavaScript方法
使用window.location.href跳转
通过修改window.location.href属性实现页面跳转,适用于直接跳转到新URL:
document.getElementById('button').onclick = function() {
window.location.href = 'https://example.com';
};
使用window.open()打开新窗口
在新标签页或窗口中打开链接,可通过参数控制行为:

document.querySelector('.link').addEventListener('click', () => {
window.open('https://example.com', '_blank');
});
通过修改location对象属性
支持assign()、replace()等方法,replace()不会保留历史记录:

// 保留历史记录
location.assign('newpage.html');
// 不保留历史记录
location.replace('newpage.html');
动态创建<a>标签跳转
适用于需要模拟点击行为的场景:
const link = document.createElement('a');
link.href = 'https://example.com';
link.target = '_blank';
link.click();
事件委托实现批量跳转
为父元素添加事件监听,动态处理子元素跳转:
document.getElementById('container').addEventListener('click', (e) => {
if (e.target.classList.contains('jump-link')) {
window.location.href = e.target.dataset.url;
}
});
注意事项
- 移动端需确保点击事件包含
touchstart或touchend处理 - 使用
preventDefault()可阻止默认跳转行为后再手动控制 - 带参数的URL需确保编码正确:
const encodedUrl = encodeURIComponent('https://example.com?param=value');






