如何使用 jQuery 更改超链接的 href 属性 [英] How to change the href attribute for a hyperlink using jQuery
问题描述
如何使用 jQuery 更改超链接的 href
属性(链接目标)?
How can you change the href
attribute (link target) 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
属性.为了安全起见,我们可以指定我们的选择器只匹配 标签与现有的
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");
});
第一部分仅选择以 http://stackoverflow.com
开头的 href 链接.然后,定义一个函数,该函数使用简单的正则表达式将 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屋!