如何在jquery中替换Anchore标签href中的一些文本

How to replace some of text in href of Anchore tag in jquery

本文关键字:href 文本 标签 Anchore jquery 替换      更新时间:2023-09-26
我很少有带有 URL 的锚点,例如"

http%3a//test.dev.test.com/posts/test test",我想在窗口加载函数上将其替换为"http://test.dev.test.com/posts/test 测试",我已经尝试了以下代码,但它没有更新锚标签的 URL。

 $('a[href*="http%3a//"]').each(function () {
      this.href = this.attr('href').replace('http%3a//', 'http://');
    });

我不明白为什么它不起作用。 请帮助我。

编辑::

<a href="http%3a//test.dev.test.com/posts/test test" rel="bookmark" class="aChangeUrl" id="ctl00_lnkEntry">New test in March</a>

>attr不是原生的DOM方法,而是jQuery方法。

改变

  this.href = this.attr('href').replace('http%3a//', 'http://');

  this.href = $(this).attr('href').replace('http%3a//', 'http://');

请注意,您可以使整体更干净,更简单:

$('a[href^="http%3a//"]').attr('href', function(_,s) {
     return s.replace('http%3a//', 'http://');
});

尝试使用.attr()函数的接收器函数来简化您的工作,

$('a[href*="http%3a//"]').attr('href', function(i,href){
      return href.replace('http%3a//', 'http://');
});

您面临的错误的原因:

this.attr('href')
----^ Here comes the problem. 'this' will point a native javascript
object at this context and it doesn't have a member function called .attr().