如何使用jQuery更改超链接的href属性

1456
你如何使用jQuery更改超链接的href属性(链接目标)?

18
针对那些希望不使用jQuery实现的解决方案,可以参考以下链接:https://dev59.com/bnVC5IYBdhLWcg3wz0h9#28016553 - Josh Crozier
2
对于较新的jQuery版本:https://dev59.com/bnVC5IYBdhLWcg3wz0h9#6348239 - Qwertiy
2
最简单的例子,不使用jQuery https://dev59.com/bnVC5IYBdhLWcg3wz0h9#39276418 - Pawel
2
一个完整的可能解决方案列表,一些有用的选择器以及获取正则表达式匹配值并将它们用于更新href的方法: https://dev59.com/bnVC5IYBdhLWcg3wz0h9#49568546 - Aman Chhabra
13个回答

2059

使用

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

将修改所有超链接的href属性,使其指向Google。但是您可能需要更精细的选择器。例如,如果您混合使用了链接源(超链接)和链接目标(又称“锚点”):

<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>

如果您不想意外地给它们添加 href 属性,那么您可能不希望这样做。为了安全起见,我们可以指定我们的选择器只匹配具有现有 href 属性的 <a> 标签:

$("a[href]") //...

当然,你可能会有更加有趣的想法。如果你想要匹配一个具有特定现有 href 的锚点,你可以使用类似以下代码:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')

这将查找链接,其中href完全匹配字符串http://www.google.com/。更复杂的任务可能是匹配,然后仅更新href的一部分:

$("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 
         "http://stackoverflow.com");
   });

第一部分仅选择href以http://stackoverflow.com开头的链接。然后,定义一个函数,使用简单的正则表达式将URL的这一部分替换为新的URL。请注意,这样可以给您带来灵活性-任何对链接的修改都可以在此处完成。


57
为了完整性考虑,因为这仍然偶尔被链接到,我会补充一下:自从 jQuery 1.4 版本以来,最后一个示例不需要使用 each - 现在可以使用以下方式:$(selector).attr('href', function() { return this.replace(/.../, '...'); }); - David Hedlund
@DavidHedlund你的函数不起作用。它会产生"this.replace不是一个函数"。 应该是:$('a[href]').attr('href', function(i, val) { return val.replace(/.*/, 'xy')}); - scr4bble
@DavidHedlund你的函数不起作用。它会产生“this.replace不是一个函数”的错误。 正确的写法是:$('a[href]').attr('href', function(i, val) { return val.replace(/.*/, 'xy')}); - undefined

315

使用jQuery 1.6及以上版本,您应该使用:

$("a").prop("href", "http://www.jakcms.com")

propattr 的区别在于,attr 获取HTML属性,而prop 获取DOM属性。

你可以在这篇文章中找到更多细节:.prop() vs .attr()


36
希望能够解释一下为什么应该使用 prop 而不是 attr,因为有些人来到这个问题时会发现在新版本的 jQuery 中 attr 看起来完美无缺。 - womble

90

使用 attr 方法查找元素。你可以使用新值替换任何属性。

$("a.mylink").attr("href", "http://cupcream.com");

49

即使OP明确要求使用jQuery,最近你不需要在所有情况下都使用jQuery。

几个不使用jQuery的方法:

  • 如果您想更改所有 <a> 元素的 href 值,请选择它们并遍历nodelist(示例)

  • var anchors = document.querySelectorAll('a');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
    如果你想要改变所有实际拥有 href 属性的 <a> 元素的 href 值,可以通过添加 [href] 属性选择器 (a[href]) 来选择它们: (示例)
    var anchors = document.querySelectorAll('a[href]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • 如果您想更改包含特定值(例如google.com)的<a>元素的href值,请使用属性选择器a[href*="google.com"](示例)

  • var anchors = document.querySelectorAll('a[href*="google.com"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
    同样地,你也可以使用其他属性选择器。例如:
    • a[href$=".png"] 可以用于选择其 href 值以 .png 结尾的 <a> 元素。

    • a[href^="https://"] 可以用于选择其 href 值以 https:// 开头的 <a> 元素。

  • 如果你想要改变同时满足多个条件的 <a> 元素的 href 值:(示例)

  • var anchors = document.querySelectorAll('a[href^="https://"], a[href$=".png"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

大多数情况下不需要正则表达式。


46

根据您是想将所有相同的链接更改为其他内容还是只想控制页面中某个部分或每个链接的链接,您可以执行以下操作之一。

将所有链接更改为指向谷歌地图的链接:

<a href="http://www.google.com">

$("a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');
为了更改指定部分中的链接,请将容器div的类添加到选择器中。以下示例将更改内容中的Google链接,但不会更改页脚中的链接:
<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$(".content a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');
要更改文档中任何位置的单个链接,请在链接上添加一个id,然后将该id添加到选择器中。此示例将更改内容中的第二个Google链接,但不会更改第一个链接或页脚中的链接:
<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
    <p>...second link to <a href="http://www.google.com/" 
        id="changeme">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$("a#changeme").attr('href', 
'http://maps.google.com/');

16
尝试这个;
$("#link").attr("href", "https://coenvink.com/")

代码的功能细节:

$("#link")

这段代码获取带有id“Link”的元素。之后,您将属性“href”(即链接到URL的链接)设置为新的URL,该URL在本例中是我的网站:

.attr("href", "https://coenvink.com/")

我希望现在已经清楚了!


15

实现这个功能的简单方法是:

Attr函数(自jQuery 1.0版本起)

$("a").attr("href", "https://stackoverflow.com/") 

或者

Prop函数(自jQuery版本1.6以来)

$("a").prop("href", "https://stackoverflow.com/")
此外,以上方法的优点在于如果选择器只选择单个锚点,则仅更新该锚点,如果选择器返回一组锚点,则仅通过一个语句更新该特定组。
现在,有很多方法可以识别具体的锚点或锚点组:
一些相当简单的方法:
1. 通过标签名称选择锚点:$("a") 2. 通过索引选择锚点:$("a:eq(0)") 3. 选择特定类的锚点(例如,在此类中仅选择具有active类的锚点):$("a.active") 4. 选择具有特定ID的锚点(例如,在示例中选择profileLink ID):$("a#proileLink") 5. 选择第一个锚点的href:$("a:first") 更实用的方法:
6. 选择所有带href属性的元素:$("[href]") 7. 选择所有具有特定href的锚点:$("a[href='www.stackoverflow.com']") 8. 选择所有没有特定href的锚点:$("a[href!='www.stackoverflow.com']") 9. 选择所有具有包含特定URL的href的锚点:$("a[href*='www.stackoverflow.com']") 10. 选择所有具有以特定URL开头的href的锚点:$("a[href^='www.stackoverflow.com']") 11. 选择所有具有以特定URL结尾的href的锚点:$("a[href$='www.stackoverflow.com']") 现在,如果您想修改特定的URL,可以按如下方式执行:
例如,如果您想为所有前往google.com的URL添加代理网站,则可以实现如下:
$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

13

仅出于需要而使用jQuery是不必要的!使用纯JavaScript就足够简单了。

document.querySelector('#the-link').setAttribute('href', 'http://google.com');

https://jsfiddle.net/bo77f8mg/1/


12

当点击一个类名为"menu_link"的链接时,此代码片段会被触发,它会显示该链接的文本和URL。使用return false可以防止链接被跟踪。

<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>

$('.menu_link').live('click', function() {
   var thelink = $(this);
   alert ( thelink.html() );
   alert ( thelink.attr('href') );
   alert ( thelink.attr('rel') );

   return false;
});

9

href是一个属性,你可以使用纯JavaScript更改它,但如果您已经在页面中注入了jQuery,不用担心,我将展示两种方法:

想象一下您有以下href

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

您希望更改链接......

使用纯JavaScript而不使用任何库,您可以执行以下操作:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

但是在 jQuery 中你也可以这样做:

$("#ali").attr("href", "https://stackoverflow.com");

或者

$("#ali").prop("href", "https://stackoverflow.com");

在这种情况下,如果您已经注入了jQuery,则可能会使用jQuery更短且更跨浏览器的方式...但除此之外,我会选择JS...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接