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

时间:2008-10-07 18:17:34

标签: javascript jquery hyperlink

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

12 个答案:

答案 0 :(得分:1730)

使用

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

会修改所有超链接的href以指向Google。你可能想要一个更精致的选择器。例如,如果您混合使用链接源(超链接)和链接目标(a.k.a。“anchor”)锚标记:

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

...然后你可能不想意外地向他们添加href属性。为安全起见,我们可以指定我们的选择器仅将<a>标记与现有的href属性匹配:

$("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的这一部分替换为新部分。请注意这为您提供的灵活性 - 可以在此处对链接进行任何类型的修改。

答案 1 :(得分:274)

使用jQuery 1.6及更高版本,你应该使用:

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

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

您可以在此信息中找到更多详细信息:.prop() vs .attr()

答案 2 :(得分:73)

在查找中使用attr方法。您可以使用新值切换任何属性。

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

答案 3 :(得分:38)

根据您是否要将所有相同的链接更改为其他内容,或者您​​希望仅控制页面的给定部分或每个部分中的链接,您可以执行以下操作之一。

更改指向Google的所有链接,以便他们指向Google地图:

<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/');

答案 4 :(得分:33)

尽管OP明确要求提供jQuery答案,但是现在你不需要使用jQuery。

一些没有jQuery的方法:

  • 如果您要更改 所有 href元素的<a>值,请全部选中,然后遍历{ {3}}: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]):(example)

    var anchors = document.querySelectorAll('a[href]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • 如果要更改包含特定值的href元素的<a>值,例如google.com,请使用属性选择器a[href*="google.com"](example)

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

    同样,您也可以使用其他(example)。例如:

    • a[href$=".png"]可用于选择<a>值以href结尾的.png个元素。

    • a[href^="https://"]可用于选择<a>元素,其href带前缀 https://

  • 如果您想更改满足多个条件的href元素的<a>值:attribute selectors

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

..在大多数案例中不需要正则表达式。

答案 5 :(得分:9)

此片段在单击“menu_link”类的链接时调用,并显示链接的文本和网址。返回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;
});

答案 6 :(得分:6)

为了它而停止使用jQuery!仅使用JavaScript非常简单。

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

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

答案 7 :(得分:5)

这样做的简单方法是:

Attr function(自jQuery版本1.0起)

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

Prop function(自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. 更有用的:

    1. 选择具有href属性的所有元素:$("[href]")
    2. 选择具有特定href的所有锚点:$("a[href='www.stackoverflow.com']")
    3. 选择所有没有特定href的锚点:$("a[href!='www.stackoverflow.com']")
    4. 选择包含特定网址的href的所有锚点:$("a[href*='www.stackoverflow.com']")
    5. 选择所有以特定网址开头的href的锚点:$("a[href^='www.stackoverflow.com']")
    6. 选择href以特定网址结尾的所有锚点:$("a[href$='www.stackoverflow.com']")
    7. 现在,如果您想修改特定的网址,可以这样做:

      例如,如果您要为google.com的所有网址添加代理网站,可以按照以下方式实施:

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

答案 8 :(得分:3)

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

答案 9 :(得分:2)

更改Wordpress Avada主题徽标图像的HREF

如果您安装了ShortCode Exec PHP插件,您可以创建我称之为myjavascript的短代码

?><script type="text/javascript">
jQuery(document).ready(function() {
jQuery("div.fusion-logo a").attr("href","tel:303-985-9850");
});
</script>

您现在可以转到外观/窗口小部件并选择其中一个页脚窗口小部件区域并使用文本窗口小部件添加以下短代码

[myjavascript]

选择器可能会根据您使用的图像以及是否准备好视网膜而改变,但您可以通过使用开发人员工具来解决它。

答案 10 :(得分:1)

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一个...

答案 11 :(得分:-1)

server {
    listen 5000;
    listen [::]:5000;
    server_name localhost;
    root E:\NG9B2C\B2C\dist\B2C\browser;
  
    http2_max_field_size 64k;
    http2_max_header_size 512k;
  
    location / {
        proxy_pass http://127.0.0.1:4000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_http_version 1.1;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    
    location /YTB/api {
             
        proxy_pass http://localhost:8073/YTB/api/;   
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_http_version 1.1;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
        proxy_connect_timeout 1600;
        proxy_send_timeout 1600;
        proxy_read_timeout 1600;
        send_timeout 1600;
        proxy_set_header X-Forwarded-Proto $scheme;
    }