如何使用jQuery更改超链接的href [英] How to change the href for a hyperlink using jQuery

查看:100
本文介绍了如何使用jQuery更改超链接的href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can you change the href for a hyperlink using jQuery?

推荐答案

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

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

...Will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:

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

...然后你可能不想意外地将 href 属性添加到它们。为了安全起见,我们可以指定我们的选择器只会匹配< a> 标签,其中包含现有的 href 属性:

...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:

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

当然,你可能会想到一些更有趣的东西。如果你想将锚点与特定的现有 href 匹配,你可能会使用类似的东西这个:

Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

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

这将找到 href 与字符串 http://www.google.com/ 完全匹配的链接。更复杂的任务可能匹配,然后只更新部分 href

This will find links where the href exactly matches the string http://www.google.com/. A more involved task might be matching, then updating only part of the 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的这一部分替换为新部分。请注意这为您提供的灵活性 - 可以在此处对链接进行任何修改。

The first part selects only links where the href starts with http://stackoverflow.com. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.

这篇关于如何使用jQuery更改超链接的href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆