如何使用 jQuery 或 Javascript 将字符串附加到 <a href=" ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17746737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:53:09  来源:igfitidea点击:

how to append string to <a href=" with jQuery or Javascript?

javascriptjqueryappend

提问by user9371102

I've the elements as follows,

我的元素如下,

<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

这样我就可以将“a”数据值用于下一页。任何人都可以给我代码,它在里面做附加

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

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

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

我想用另一个 onChange 事件删除添加的文本。

Thanks in advance

提前致谢

回答by Karl-André Gagnon

Since jquery is tagged :

由于 jquery 被标记为:

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

Vanilla JS would look like this :

Vanilla JS 看起来像这样:

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

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

回答by Blazemonger

.attr(), like many jQuery functions, can take a function argument that modifies the existing value:

.attr(),像许多 jQuery 函数一样,可以采用修改现有值的函数参数:

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

回答by Bar?? U?akl?

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

回答by Aamir Shah

Simply use the attr property. Example :-

只需使用attr property. 例子 :-

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

This will do the job.

这将完成工作。

回答by vikrant singh

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

回答by Lucas Willems

Try this code :

试试这个代码:

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

回答by Khawer Zeshan

you can use attrmethod

你可以使用attr方法

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

And if you want to change the hrefof a specific <a>give that '' a unique id and than change its hrefas follows

如果你想改变href一个特定的<a>给那个 '' 一个唯一的 id 然后改变它href如下

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