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

4 Answers 4

2

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));
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

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

Cheer ^^

Comments

1

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')));
    });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.