jQuery来更改页面中的所有链接

$(function(){ $('a').each(function(){ var x=this.href; this.href="www.somesitename.com/filter"+this.href; }); }); 

我写了上面的jQuery脚本,将一些网站名称附加到页面中的所有链接,但它没有按预期工作。

我想知道为什么你会使用jQuery这样的基本行为…

这就是BASE标签的原因

为页面上的所有链接指定默认URL默认目标

       W3Schools  

不要简单的复杂化!


添加

来自Sitepoint

如果您的所有相关链接表单提交都转到同一位置,那么基本元素将对您有用。

您可能需要添加http://

 $(function(){ $('a').each(function() { $(this).attr('href', 'http://www.somesitename.com/filter' + this.href); }); }); 

进一步改进Darin的解决方案:

 $(function(){ $('a').attr('href', (n, old) => 'http://www.somesitename.com/filter' + old); }); 

需要注意的是,在.each的情况下, this.href会生成一个绝对的完全限定URL(例如: http:// localhost:8888 / mylink ),因此结果可能如下所示: http://www.somesitename.com/filter/http :// localhost:8888 / mylink 。 解决方案是通过jQuery获取属性值:$(this).attr(’href’),它正确地产生/ mylink

在头部定义一个基本标签,然后在需要时更新它的href属性。

  $("base").attr("href","http://www.some-other-domain.com/"); 

这是我过去常常这样做的

我已从页面上的href删除了每个’blog /’,您可以更改链接或更新链接

$('a').each(function(){ var updated_link = $(this).attr('href').replace('blog/', ''); $(this).attr('href', updated_link); });

我已经使用replace函数来更新url的一部分。在你的情况下,你可以更新它

你可能需要使用append()函数,jQuery有http://api.jquery.com/append/