【问题标题】:jQuery: replace If this HREF containsjQuery:替换如果此 HREF 包含
【发布时间】:2021-04-14 10:18:38
【问题描述】:

我想使用 jQuery 将一个附属链接替换为另一个。我想找到所有redirect.affiliatelink1.com 开始 的链接,并将其替换为api.affiliatelink2.com

jQuery(document).ready(function($) {
  $('.post-body-inner a').each(function() {
    if ($(this).is('[href$=redirect.affiliatelink1.com]')) {
      $(this).attr('href', 'https://api.affiliatelink2.com');
    }
  });
});

【问题讨论】:

    标签: jquery replace hyperlink


    【解决方案1】:

    您的代码中有几个问题。首先,属性选择器中的$= 用于“结束于”匹配。要匹配属性值的开头,请使用^=

    其次,您需要替换现有值,而不是仅用新 URL 覆盖整个内容。

    最后,您可以通过向attr() 提供一个函数来简化逻辑,该函数针对所有选定的a 元素执行,而不是显式的each() 循环。

    说了这么多,试试这个:

    jQuery($ => {
      $('.post-body-inner a').attr('href', (i, h) => h.replace('https://redirect.affiliatelink1.com', 'https://api.affiliatelink2.com'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="post-body-inner">
      <a href="https://redirect.affiliatelink1.com/foo">Foo</a>
    </div>

    【讨论】:

    • 它正在工作 - 但我想替换所有 href 内容 - 我的附属链接看起来像“redirect.affiliatelink1.com/?utm_medium=cpt&utm_content=affiliate&utm_campaign=100” - 我想要替换所有href内容不仅是主域
    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 2015-12-03
    • 1970-01-01
    • 2011-05-18
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多