开发者

Replace href with jQuery, regular expression

开发者 https://www.devze.com 2023-03-29 07:44 出处:网络
I have a bunch of href links that need to be replaced: <a id=\"link\" href=\"http://localhost:8091/tabid/99/catid/8/page1.aspx\">Page1</a>

I have a bunch of href links that need to be replaced:

<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>

The href should be changed to: "http://localhost开发者_开发百科:8091/tabid/1/catid/8/page1.aspx"

By searching I found:

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

This should do the job. However, it only replaces one of the links. Could anyone help me with the regular expression here? I need to change all the numbers in tabid/**/catid to "1".


Your problem is using an id to access multiple elements: an id, according to the specification, must be unique in the document. Using an id causes JavaScript to return the first element it finds, rather than continuing searching through the document (since there must be only one).

To use the same name for multiple elements use a class instead:

<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>

With amended jQuery:

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


The id attribute specifies a unique id for an HTML element. In your case they are not unique. Try using css selectors or target all "a" elements.


First, change id to class. Second, make this change:

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

Now it only replaces the numbers after tabid, not just any number anywhere in the string.


A id is unique in the document, you should use class instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消