2013-07-19 11 views
11

I've the elements as follows,come accodare stringa per <a href=" with jQuery or Javascript?

<div id="pager"> 
<a href="/somepath/1">First</a> 
<a href="/somepath/1">Previous</a> 
<a class="" href="/somepath/1">1</a> 
<a class="Current" href="/somepath/2">2</a> 
<a class="" href="/somepath/3">3</a> 
<a href="/somepath/3">Next</a> 
<a href="/somepath/20">Last</a> 
</div> 

and I want it to be changed as follows within browser.

<div id="pager"> 
<a href="/somepath/1?a=text">First</a> 
<a href="/somepath/1?a=text">Previous</a> 
<a class="" href="/somepath/1?a=text">1</a> 
<a class="Current" href="/somepath/2?a=text">2</a> 
<a class="" href="/somepath/3?a=text">3</a> 
<a href="/somepath/3?a=text">Next</a> 
<a href="/somepath/20?a=text">Last</a> 
</div> 

So that I can use the "a" data values to next page. Can any one give me the code, which does the appends inside

div id="pager" -><a> ->href="

and i wants to remove the added text with another onChange event.

Thanks in advance

risposta

25

Poiché jquery è taggato:

$('#pager a').each(function(){ 
    this.href += '?a=text'; 
}) 

Vanilla JS sarebbe simile a questa:

var a = document.getElementById('pager').getElementsByTagName('a'), 
    length = a.length; 

for(var i=0; i< length; i++){ 
    a[i].href += '?a=text'; 
} 
+2

-1 per "childrens" (no, non proprio) – Blazemonger

+0

@Blazemonger Cosa intendi? il nome var è sbagliato? –

+0

@Bondye Cosa c'è di sbagliato nella funzione '.each'? * "+ 1 Finalmente uno senza la funzione .each() ... Le persone non capiscono .each() .." *. La risposta in cui hai postato questo commento, cosa pensi che succeda dietro il codice? Inoltre, '.each()' è più veloce: http://jsperf.com/each-vs-function –

2

you can use attr metodo

$('a').attr('href', '/somepath/1?a=text'); 

E se si desidera modificare il href di uno specifico <a> danno che '' un ID univoco e di cambiare il suo href come segue

$('#link').attr('href', '/somepath/1?a=text'); 
6
$('#pager a').each(function() { 
    $(this).attr('href', $(this).attr('href') + '?a=text'); 
}); 
+0

Grazie, aggiornato la questione – user9371102

5

è sufficiente utilizzare il attr property. Esempio: -

$("a").attr("href", "http://www.google.com/") 

Questo farà il lavoro.

12

.attr(), come molte funzioni jQuery, può prendere un argomento di funzione che modifica il valore esistente:

$('#pager a').attr('href',function(i,str) { 
    return str + '?a=text'; 
}); 
+0

Mi piace questo uno –

+0

@Blazemonger Grazie e io Accetterò la risposta di Karl-André Gagnon. Hai wow ans e come rimuovere il testo aggiunto "? A = text" con l'altro evento onChange? – user9371102

+0

"return str.split ('?') [0];" dovrebbe farlo – Blazemonger

2

provare questo codice:

$('#pager a').each(function(){ 
    this.href += '?a=text' 
}) 
3
$("#pager").find("a").each(function(){ 
var $this=$(this); 
$this.attr("href",$this.attr("href")+"?a=text"); 
}) 
Problemi correlati