Jos*_*ies 8 html javascript url jquery
我正在尝试在新窗口中打开网站上的所有外部链接.但是,该网站有2个版本.例如商店和主要网站.因此,在主站点上,我们可能会有链接到http://store.site.com.
我在这里有一些代码可以让我在新窗口中打开所有外部链接.但是,我希望能够排除某些域名.就像我上面提到的那个.
这是代码:
$(document).ready(function() {
$("a[href^=http]").each(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
}
})
});
Run Code Online (Sandbox Code Playgroud)
我是JS/Jquery的新手,所以很多信息都很棒.
tec*_*bar 13
要以编程方式触发点击,您可以执行以下操作:
$(document).ready(function() {
$("a[href^=http]").each(function(){
// NEW - excluded domains list
var excludes = [
'excludeddomain1.com',
'excludeddomain2.com',
'excluded.subdomain.com'
];
for(i=0; i<excludes.length; i++) {
if(this.href.indexOf(excludes[i]) != -1) {
return true; // continue each() with next link
}
}
if(this.href.indexOf(location.hostname) == -1) {
// attach a do-nothing event handler to ensure we can 'trigger' a click on this link
$(this).click(function() { return true; });
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
$(this).click(); // trigger it
}
})
});
Run Code Online (Sandbox Code Playgroud)
如果您只想获取与您的域名不匹配的所有链接:
var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++){
var a = all_links[i];
if(a.hostname != location.hostname) {
a.rel = 'noopener';
a.target = '_blank';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11222 次 |
| 最近记录: |