如何用JavaScript/jQuery强制外部链接及横幅广告在新窗口打开?
我懂你这种挫败感——翻遍相关帖子试了各种代码,结果横幅广告还是在当前窗口跳转,外部链接也不听话?别慌,我给你几个亲测有效的方案,不管是用jQuery还是原生JS都能搞定:
jQuery 实现方案(兼容动态加载元素)
这种方法能覆盖页面初始加载的元素,以及后续动态添加的广告/链接(比如异步加载的横幅):
$(document).on('click', 'a', function(e) { const $link = $(this); const targetUrl = $link.attr('href'); // 判断是否是横幅广告链接,或是外部链接 const isBannerAd = $link.closest('.bannerad').length > 0; const isExternal = targetUrl && targetUrl.startsWith('http') && !targetUrl.includes(window.location.hostname); if (isBannerAd || isExternal) { e.preventDefault(); // 阻止默认的当前窗口跳转 window.open(targetUrl, '_blank'); // 在新窗口打开链接 } });
小说明:
- 用
$(document).on做事件委托,能捕获到后续动态插入DOM的广告元素,不会漏掉 closest('.bannerad')能精准定位到嵌套在.bannerad容器里的所有链接,不管层级多深- 外部链接的判断逻辑:只要链接以
http开头,且不包含当前网站的域名,就判定为外部链接
如果你的横幅广告本身就是带.bannerad类的<a>标签,也可以简化写法:
$(document).on('click', '.bannerad, a[href^="http"]:not([href*="' + window.location.hostname + '"])', function(e) { e.preventDefault(); window.open($(this).attr('href'), '_blank'); });
原生 JavaScript 实现方案(无依赖)
如果你的项目没用到jQuery,用原生JS也能实现同样的效果:
document.addEventListener('click', function(e) { // 找到点击元素对应的<a>标签(即使点的是a内部的图片/文字) const link = e.target.closest('a'); if (!link) return; const targetUrl = link.getAttribute('href'); if (!targetUrl) return; const isBannerAd = link.closest('.bannerad') !== null; const isExternal = targetUrl.startsWith('http') && !targetUrl.includes(window.location.hostname); if (isBannerAd || isExternal) { e.preventDefault(); window.open(targetUrl, '_blank'); } });
避坑小贴士
- 如果遇到广告自带
onclick事件覆盖了我们的代码,可以试试在e.preventDefault()前加上e.stopPropagation(),阻止事件冒泡(注意:可能会影响页面其他事件,测试后再用) - 记得把代码放在DOM加载完成后执行:
// 原生JS写法 document.addEventListener('DOMContentLoaded', function() { // 上面的原生JS代码放这里 }); // jQuery写法 $(document).ready(function() { // 上面的jQuery代码放这里 });
内容的提问来源于stack exchange,提问作者user9860866
相关产品推荐
相关产品推荐

