需求说明
需要在JS代码中打开新的页面,且需要在浏览器的新标签页面中打开
实现
一般使用一下代码打开新页面
window.location.href='https://www.baidu.com';
window.open('https://www.baidu.com');
不过并不是在新标签页中打开的,可以这样做:
window.open('https://www.baidu.com', '_blank');
另一种方式:
function openInNewTab(url) {
Object.assign(document.createElement('a'), {
target: '_blank',
rel: 'noopener noreferrer',
href: url,
}).click();
}
第三种方式:
function openInNewTab(url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
document.body.appendChild(link);
link.click();
link.remove();
}
文章评论