javascript noob试图找出一些东西。我在这里看到了一个脚本:
Using jQuery to open all external links in a new window
检查页面上的网址以查看它们是否与当前网页网址匹配。如果没有,这个特定的脚本将在新窗口中打开它们。我想在网址上使用相同的测试,但如果它们是外部的我想要?iframe要附加到每个网址,一个la fancybox语法。我的noob脚本是:
$(document).ready(function() {
$('a[@href^="http://"]').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).append('?iframe')
});
我认为这是不正确的。任何帮助?感谢
答案 0 :(得分:1)
您必须使用attr
更改href
属性,而不是append
个新的子元素:
$('a[href^="http://"]').filter(function() { // no @ before the attribute name
return this.hostname && this.hostname !== location.hostname;
}).attr('href', function(i, value) {
// takes care of URLs with parameters
return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe';
});
请注意,hostname
为only available in HTML5。因此,在不支持HTML 5的浏览器中,过滤器会丢弃每个元素(更新:鉴于您链接的问题来自2009年,似乎浏览器实现了hostname
,但它不是任何规范的一部分)。您可以将其更改为:
var hostname = new RegExp("^http://" + location.hostname);
$('a[href^="http://"]').filter(function() {
return !hostname.test(this.href);
}).attr('href', function(i, value) {
return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe';
});
如果您还想将链接转换为https
网站,请抛弃属性选择器并更改正则表达式:
var hostname = new RegExp("^https?://" + location.hostname);
$('a').filter(function() {...
<强>更新强>
特别是对于fancybox,根据documentation,它应该以这种方式工作。但是,你是对的,你可以添加iframe
类:
$('a').filter(function() {...}).addClass('iframe');
答案 1 :(得分:0)
修改href属性,而不是append,它修改了元素的内部HTML:
$(document).ready(function() {
var elements = $('a[@href^="http://"]').filter(function() {
return this.hostname && this.hostname !== location.hostname;
});
elements.each(function(index, value) {
$(this).attr('href', $(this).attr('href') + '?iframe');
});
});
答案 2 :(得分:0)
您对append
方法的使用不正确。以下代码显示了如何实现您的需求,此外还考虑了您需要记住的几个其他因素,即:
1)使用https而不是http的链接呢? 2)那些已经包含查询字符串参数的链接呢? http://www.blah.com/?something=123应更改为http://www.blah.com/?something=123&iframe而不是http://www.blah.com/?something=123?iframe
$(function() {
$('a[href^="http"]').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).each(function() {
this.href += ((this.href.indexOf('?') >= 0) ? '&' : '?') + 'iframe';
});
});