【问题标题】:Replace href with jQuery, regular expression用jQuery替换href,正则表达式
【发布时间】:2011-10-29 05:44:39
【问题描述】:

我有一堆 href 链接需要更换:

<a id="link" href="http://localhost:8091/tabid/99/catid/8/page1.aspx">Page1</a>
<a id="link" href="http://localhost:8091/tabid/98/catid/8/page1.aspx">Page1</a>
<a id="link" href="http://localhost:8091/tabid/97/catid/8/page1.aspx">Page1</a>

href 应改为: "http://localhost:8091/tabid/1/catid/8/page1.aspx"

通过搜索发现:

$(document).ready(function () {
    $("#link").each(function () {
        this.href = this.href.replace("99", "1");
    });
});

这应该可以完成工作。但是,它只替换了其中一个链接。任何人都可以在这里帮助我使用正则表达式吗?我需要将tabid/**/catid 中的所有数字更改为“1”。

【问题讨论】:

  • 您有多个具有相同 id 的元素...这是无效的。将您的 id 更改为 classes

标签: javascript jquery regex href


【解决方案1】:

您的问题是使用id 访问多个元素:idaccording to the specification在文档中必须是唯一的。使用 id 会导致 JavaScript 返回它找到的第一个元素,而不是继续搜索文档(因为 必须只有一个)。

要对多个元素使用相同的名称,请改用class

<a class="link" href="http://localhost:8091/tabid/**99**/catid/8/page1.aspx">Page1</a>
<a class="link" href="http://localhost:8091/tabid/**98**/catid/8/page1.aspx">Page1</a>
<a class="link" href="http://localhost:8091/tabid/**97**/catid/8/page1.aspx">Page1</a>

使用修改后的 jQuery:

$(document).ready(function () {
    $(".link").each(function () {
        this.href = this.href.replace("99", "1");
    });
});

【讨论】:

    【解决方案2】:

    id 属性为 HTML 元素指定一个唯一的 id。在您的情况下,它们不是唯一的。尝试使用 css 选择器或定位所有“a”元素。

    【讨论】:

      【解决方案3】:

      首先,将 id 更改为 class。其次,进行此更改:

      this.href = this.href.replace(/tabid\/\d+/i, '/tabid/1');
      

      现在它只替换 tabid 之后的数字,而不是字符串中的任何数字。

      【讨论】:

      • 那么无论如何,+1 答案,以便未来的观众知道。我得到了我的 +15 破解。
      【解决方案4】:

      一个id在文档中是唯一的,你应该使用class来代替。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-12
        • 1970-01-01
        • 2011-07-09
        • 1970-01-01
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 2019-01-24
        相关资源
        最近更新 更多