jquery 在新窗口打开外部链接

2015-01-19 22:45

$('a').each(function() {

var a = new RegExp('/' + window.location.host + '/');

if(!a.test(this.href)) {

$(this).click(function(event) {

event.preventDefault();

event.stopPropagation();

window.open(this.href, '_blank');

});

}

});

当然你也可以在html中设置A标签的target属性为_blank实现。 但是有时候html内容是用户发表的,我们没法修改用户内容中的A标签,但是我们可以在页面上通过脚本控制。

下面的一行代码可以设置以http://开头的链接在新窗口打开。

$("#content a[href^='http://']").attr("target","_blank");

^