1

I have:

<span id="test"><a href="google.com/">link1</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')+$(this).attr('id'));
});

LIVE: http://jsfiddle.net/wtAbp/10/

if i click one i have:

google.com/1

this is ok, but if i again click, for example click two i have:

google.com/12

instead of:

google.com/2

how can i fix it?

3 Answers 3

4

Do

$("a").attr('href', 'http://google.com/'+$(this).attr('id'));

Or

$("a").attr('href', $("a").attr('href').replace(/\d*$/, $(this).attr('id')));
Sign up to request clarification or add additional context in comments.

Comments

1

You could add a data field to hold the original URL -

<span id="test"><a data-url="google.com/" href="google.com/">link1</a></span> 

Then change your jQuery code to look up the data attribute rather than the href -

$(".click").live('click', function() {    
    $("a").attr('href',$("a").data('url')+$(this).attr('id'));
});

Working demo - http://jsfiddle.net/hz6Fr/

Comments

1

problem is you are using

$("a").attr('href',$("a").attr('href')+$(this).attr('id'));

after updation of link first time a herf is google.com/1

so when you query it next time remove the value after / from the link

Second time

var href = $("a").attr('href').substring(0,$("a").attr('href').lastIndexOf('/'))

final code

    $(".click").live('click', function() { 
        var href ;
if ( $("a").attr('href').substring(0,$("a").attr('href').lastIndexOf('/')) >0)
  href= $("a").attr('href').substring(0,$("a").attr('href').lastIndexOf('/'));   
else 
  href= $("a").attr('href'); 
        $("a").attr('href',href + $(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.