Paul Wichy
Paul Wichy

Reputation: 47

regex + jquery - modify text

<span id="one"><a id="google" href="google.com/">link1</a></span> <br />
<span id="two"><a id="yahoo" href="yahoo.com/">link2</a></span>

<br />
<br />
<span class="click" id=1>click one</span> <br />
<span class="click" id=2>click two</span> <br />
<span class="click" id=3>click three</span> <br />

$(".click").live('click', function() {    
   $("a").attr('href', $("a").attr('href').replace(/\d*$/, $(this).attr('id')));
});

If I click for example click one then links are:

<span id="one"><a id="google" href="google.com/1">link1</a></span> <br />
<span id="two"><a id="yahoo" href="google.com/1">link2</a></span>

instead of:

<span id="one"><a id="google" href="google.com/1">link1</a></span> <br />
<span id="two"><a id="yahoo" href="yahoo.com/1">link2</a></span>

LIVE EXAMPLE: http://jsfiddle.net/wtAbp/14/

How can I fix it?

Upvotes: 1

Views: 121

Answers (4)

Richard
Richard

Reputation: 22016

The reason is that when you click one it replaces the values on all a elements. Try this:

<span id="one"><a id="google" href="google.com/">link1</a></span> <br />
<span id="two"><a id="yahoo" href="yahoo.com/">link2</a></span>

<br />
<br />
<span class="click" id=1>click one</span> <br />
<span class="click" id=2>click two</span> <br />
<span class="click" id=3>click three</span> <br />

$(".click").live('click', function() {    
    var $this = $(this);
    $.each("a", function(index, element) {
              $(element).attr('href',            $(element).attr('href').replace(/\d*$/, $this.attr('id')));
    });

});

Upvotes: 1

Kent
Kent

Reputation: 2960

$(".click").live('click', function() {
    var id = $(this).attr('id');
    $("a").each(function() {
        $(this).attr('href', $(this).attr('href').replace(/\d*$/, id));
    });
});

Cheer ^^

Upvotes: 1

Dogbert
Dogbert

Reputation: 222128

You're using $("a") instead of $(this)

$(".click").live('click', function() {    
   $(this).attr('href', $(this).attr('href').replace(/\d*$/, $(this).attr('id')));
});

Upvotes: 1

Samich
Samich

Reputation: 30105

Here is working sample http://jsfiddle.net/wtAbp/18/

$(".click").live('click', function() {  
    var $id = $(this).attr('id');
    $("a").each(function() {
        $(this).attr('href', $(this).attr('href').replace(/\d*$/, $id));
    });
});

Upvotes: 2

Related Questions