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


当前回答

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");

or

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

在这种情况下,如果您已经注入了jQuery,那么jQuery可能看起来更短,更跨浏览器。。。但除此之外,我会选择JS的。。。

其他回答

尽管OP明确要求jQuery的答案,但现在您不需要对所有事情都使用jQuery。

一些没有jQuery的方法:

如果要更改所有<a>元素的href值,请将其全部选中,然后遍历节点列表:(示例)var anchors=document.querySelectorAll('a');Array.protocol.forEach.call(锚,函数(元素,索引){element.href=“http://stackoverflow.com";});如果要更改实际具有href属性的所有<a>元素的href值,请通过添加[href]属性选择器(a[href]])来选择它们:(示例)var anchors=document.querySelectorAll('a[href]');Array.protocol.forEach.call(锚,函数(元素,索引){element.href=“http://stackoverflow.com";});如果要更改包含特定值的<a>元素的href值,例如google.com,请使用属性选择器a[href*=“google.com”]:(示例)var anchors=document.querySelectorAll('a[href=“google.com”]');Array.protocol.forEach.call(锚,函数(元素,索引){element.href=“http://stackoverflow.com";});同样,您也可以使用其他属性选择器。例如:a[href$=“.png”]可用于选择href值以.png结尾的<a>元素。a[href^=“https://”]可用于选择具有前缀为https://的href值的<a>元素。如果要更改满足多个条件的<a>元素的href值:(示例)var anchors=document.querySelectorAll('a[href=“https://”],a[href=“.png”]');Array.protocol.forEach.call(锚,函数(元素,索引){element.href=“http://stackoverflow.com";});

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

在查找时使用attr方法。您可以使用新值关闭任何属性。

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

当单击类“menu_link”的链接时,此代码段将调用,并显示链接的文本和url。返回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;
});

更改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]

选择器可能会根据您使用的图像以及视网膜是否就绪而改变,但您始终可以使用开发人员工具来确定。

不要为了jQuery而使用它!仅使用JavaScript就非常简单。

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

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