我希望网站中的链接在网站(导航,内部网页链接)中引导您正常打开,但是在新窗口中打开外部源的链接。
放置目标=" _blank"由于webkit浏览器忽略了这一点,因此HTML不再是一个选项,所以我需要使用JavaScript。
我如何使用JS在新窗口中打开页面上的所有绝对URL并保留所有相对URL? (这是我用来区分两者的方法。)
我想它将成为以下版本的扩展版本:
onclick="window.open(''); return false;"
但剩下的就超出了我......
我更愿意避免使用类或ID(事实上,由于CMS限制,id不可能)因为我更喜欢将标记保持为最小和语义可能的。
答案 0 :(得分:3)
选择器过滤外部链接。点击一个新窗口将被打开。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<!-- Here is your site content -->
<script>
$(document).ready(function() {
$('a[href^="http://"]').on('click', function(e) {
e.preventDefault();
window.open($(this).attr('href'), '_new');
});
});
</script>
</body>
</html>
此外,您可以使用以下代码段:
$('a').on('click', function(e) {
e.preventDefault();
var domain = 'http://example.com',
url = $(this).attr('href'),
target = '_top';
if (this.href.indexOf(domain) !== 0) {
target = '_new';
}
window.open(url, target);
});
答案 1 :(得分:2)
类似的东西:
var domain = "http://example.com";
$("a").onclick(function () {
if (this.href.indexOf(domain) !== 0) {
window.open(this.href);
return false;
}
return true;
});
它会将onclick处理程序附加到页面上的所有<a>
。如果链接看起来像是指向外部网站:打开一个新窗口而取消默认点击事件(return false
),如果没有,继续(return true
)