2013-07-19 13 views
11

I've the elements as follows,jak dołączyć ciąg <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

Odpowiedz

25

Ponieważ jquery jest oznaczony tagiem:

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

Vanilla JS będzie wyglądać następująco:

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

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

-1 dla "dzieci" (nie, nie do końca) – Blazemonger

+0

@Blazemonger Co masz na myśli? nazwa var jest błędna? –

+0

@Bondye Co jest nie tak z funkcją '.each'? * "+ 1 W końcu jedna bez tej funkcji .each() ... Ludzie nie rozumieją .each() .." *. Odpowiedź na pytanie, gdzie opublikowałeś ten komentarz, co według Ciebie dzieje się za kodem? Ponadto, '.each()' jest szybsze: http://jsperf.com/each-vs-function –

2

you can use attr metoda

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

A jeśli chcesz zmienić href konkretnego <a> podać, że „” unikatowy identyfikator i niż zmienić jego href jak następuje

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

Thanks, uaktualnione pytanie – user9371102

5

Wystarczy użyć attr property. Przykład: -

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

To wykona zadanie.

12

.attr(), jak wiele funkcji jQuery, można przyjąć argumentu funkcja, która modyfikuje istniejącą wartość:

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

Podoba mi się to +1 –

+0

@Blazemonger Dzięki i ja Przyjmę odpowiedź Karla-André Gagnona. Masz wow i jak usunąć dodany tekst "? A = text" z innym zdarzeniem onChange? – user9371102

+0

"return str.split ("? ") [0];" powinien to zrobić. – Blazemonger

2

Spróbuj kod:

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