2011-09-06 3 views
1

J'ai:regex pour ajouter du texte - jquery

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

si je clique sur un i ai:

google.com/1

c'est ok, mais si je clique de nouveau, par exemple cliquez sur deux que j'ai:

google.com/12

au lieu de:

google.com/2

comment puis-je résoudre ce problème?

Répondre

4

Do

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

Ou

$("a").attr('href', $("a").attr('href').replace(/\d*$/, $(this).attr('id'))); 
+0

ce ne fonctionne pas: http://jsfiddle.net/wtAbp/12/ –

+0

maintenant fait: http://jsfiddle.net/wtAbp/13/ – arnaud576875

1
problème

est que vous utilisez

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

après updation de lien première fois qu'un Herf est google.com/1

donc quand vous interrogez la prochaine fois rem ove la valeur après/du lien

temps Deuxième

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

code final

$(".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')); 
    }); 
1

Vous pouvez ajouter un champ de données pour contenir l'URL d'origine -

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

Ensuite, changez votre code jQuery pour rechercher l'attribut de données plutôt que le href -

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

Démo de travail - http://jsfiddle.net/hz6Fr/

Questions connexes