jQuery替换相对链接

希望有人可以解释我在jQuery中遇到的一些奇怪的行为。 以下脚本正在寻找我页面上的相对链接,并用绝对链接替换它们。

$(document).ready(function() { $("a[href^='/']").each(function(){ var cur_href = $(this).prop("href"); $(this).prop("href", 'http://www.mysite.com'+cur_href); }); }); 

我在一个将通过https提供的页面上使用此脚本,但我不希望所有导航都链接到https页面。 由于我的导航是全局包含,这似乎是解决问题的最简单方法。

我遇到的问题出现在实际更换中。 脚本的第二行正确匹配页面上的所有相对链接,然后运行脚本的替换部分。 它在第4行的替换中,我得到了一些奇怪的结果。 在此部分脚本运行后,我的URL最终看起来像这样:

HTTP://www.mysite.comhttps//www.mysite.com/mypage.htm

显然没有做我想做的事。 看起来脚本的第一部分与相对URL匹配,但是当替换部件触发时,浏览器已经添加了域信息。

到目前为止,我发现的唯一能够实现我想要的就是编写替代品,预测浏览器已经添加了什么:

 this.href = this.href.replace(/^https:\/\/www\.mysite\.com\//, "http://www.mysite.com/"); 

有一个更好的方法吗?


编辑: 这是一个问题的解决方案 。

jQuery在这里没有引起问题。 问题是, 根据规范 ,HTMLAnchorElement的href属性(对象jQuery返回的类型)始终包含绝对URI。

在HTML5中, href是一个复合属性 ,你可以通过修改href.protocolhref.protocol交换协议( //之前的部分),例如:

 var link = $( 'bar' )[0]; console.log( link.href ); // => https://example.com/foo link.href.protocol = 'http:'; console.log( link.href ); // => http://example.com/foo 

对于没有复合href旧浏览器,您只需要使用正则表达式:

 console.log( link.href ); // => https://example.com/foo link.href = link.href.replace( /^https:/, 'http:' ); console.log( link.href ); // => http://example.com/foo 

TLDR:您的代码应如下所示:

 $( "a[href^='/']" ).prop( "href", function( _idx, oldHref ) { return oldHref.replace( /^https:/, 'http:' ); } ); 

PS你会注意到我$.each你的$.each电话。 这是因为prop自动作用于匹配集中的每个元素,即它已经完成了你对每个元素所做的事情。


.prop(propertyName,function(index,oldPropertyValue))

  • propertyName要设置的propertyName的名称。
  • function(index, oldPropertyValue)将值返回到set的函数。 接收集合中元素的索引位置和旧属性值作为参数。 在函数内,关键字this指的是当前元素。

这不是很好,但它应该适用于各种浏览器:

 $(document).ready(function() { $("a[href^='/']").each(function(){ var cur_href = $(this).attr("href"); if( cur_href.indexOf( "http" ) !== -1 ) { $(this).attr("href", cur_href); } else { $(this).attr("href", 'http://www.mysite.com'+cur_href); } }); }); 

代码:

 $(function() { $('input').click(function() { $('a').not('[href^="http"],[href^="https"],[href^="mailto:"],[href^="#"]').each(function() { $(this).attr('href', function(index, value) { if (value.substr(0,1) !== "/") { value = window.location.pathname + value; } return "http://mynewurl.com" + value; }); }); }); }); 

看到这个jsfiddle: http : //jsfiddle.net/aknosis/kWrjr/

以下是我解决此问题的链接: http : //aknosis.com/2011/07/17/using-jquery-to-rewrite-relative-urls-to-absolute-urls-revisited/

尝试这样的事情:

 if(! /http/.test( cur_href) ){ $(this).attr("href", 'http://www.mysite.com'+cur_href); } 

.prop()获取属性值而不是属性值。 虽然相似,但存在一些微妙的,重要的差异 – 其中一个适用于此。 元素上的href属性始终是完整路径。 例如:

   

换句话说,您将域附加到已经是绝对路径的值。 只需使用.attr()而不是.prop() ,你就可以了。

要查看示例,请打开控制台并转到此页面: http : //jsfiddle.net/JUcHU/

试着简单地用

 $(document).ready(function() { $("a[href^='/']").each(function(){ var cur_href = this.href; /* <-- access to the href attribute through the DOM reference */ $(this).prop("href", 'http://www.mysite.com'+cur_href); }); });