我有以下代码将target="_blank"
添加到所有链接:
$(function() {
$("a[href^='http://']").attr("target","_blank");
});
如何重新编写上述代码以定位除内部链接之外的所有链接。
IE:
http://www.my-site.com/
=内部链接
http://www.other-site.com/
=外部链接
另外,我如何定位任何不以http://
开头但不是内部的链接?
我正在寻找一个jQuery解决方案。
答案 0 :(得分:6)
只需链接您的选择器:
$("a[href^='http']:not([href^='http://www.mysite.com'])").attr("target","_blank");
这将选择所有以http
开头的链接(所以不是相对内部)但不是以http://www.mysite.com
开头(所以也不是绝对内部)。
答案 1 :(得分:4)
我在使用jQuery时使用以下JavaScript。它还为外部链接添加了一个类,并包括跟踪Google Analytics中的外发链接。如果您不使用Google Analytics,请将其删除。
如果您不希望此按钮点击页面上的所有链接,则可以使用更具体的选择器,例如$("#main a[href^=http]")
。
$("a[href^=http]")
.each(function(){
// this part checks if the link is external
if (this.href.indexOf(location.hostname) == -1){
// add a class for external links
$(this).addClass("ext")
// make the link open in a new tab/window
.attr({ "target":"_blank", "rel":"external" })
// track clicks of external links if you use Google Analytics
.click(function(){
_gaq.push(["_trackEvent", "Outgoing link", "click", $(this).attr("href")]);
});
}
});