如何使用 JavaScript 动态地向链接添加“href”属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4689344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:38:24  来源:igfitidea点击:

How can I add "href" attribute to a link dynamically using JavaScript?

javascripthtml

提问by Pavel

How can I add the hrefattribute to a link dynamically using JavaScript?

如何href使用 JavaScript 动态地将属性添加到链接?

I basically want to add a hrefattribute to <a></a>dynamically (i.e. when the user clicks on specific image in the website).

我基本上想动态添加一个href属性<a></a>(即当用户点击网站中的特定图像时)。

So from:

所以从:

<a>Link</a>

I need to go to:

我需要去:

<a href="somelink url">Link</a>

回答by stecb

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

回答by mgiuca

I assume you know how to get the DOM object for the <a>element (use document.getElementByIdor some other method).

我假设您知道如何获取<a>元素的 DOM 对象(使用document.getElementById或其他方法)。

To add any attribute, just use the setAttributemethod on the DOM object:

要添加任何属性,只需在 DOM 对象上使用setAttribute方法:

a = document.getElementById(...);
a.setAttribute("href", "somelink url");

回答by Rahul Sudha

First, try changing <a>Link</a>to <span id=test><a>Link</a></span>.

首先,尝试更改<a>Link</a><span id=test><a>Link</a></span>.

Then, add something like this in the javascript function that you're calling:

然后,在您调用的 javascript 函数中添加如下内容:

var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';

This way the link will look like this:

这样,链接将如下所示:

<a href="somelink">Link</a>

回答by no?????z???

document.getElementById('link-id').href = "new-href";


I know this is an old post, but here's a one-liner that might be more suitable for some folks.

我知道这是一篇旧帖子,但这里有一篇可能更适合某些人的单行文章。