开发者

Is it possible to change the href of a link?

开发者 https://www.devze.com 2023-02-14 20:42 出处:网络
Here I have a link: <a id=\"downloadLink\">Donwload Link</a> And a JavaScript function: function ac(){document.getElementById(\'d开发者_JAVA技巧ownloadLink\').href = \"CS352ProjectProp

Here I have a link:

<a id="downloadLink">Donwload Link</a>

And a JavaScript function:

function ac(){document.getElementById('d开发者_JAVA技巧ownloadLink').href = "CS352ProjectProposalRequirements.pdf";}

However when I call the function it doesn't work. It gives an error:

Cannot change the property of null "href"

How can I dynamically change the href of a link?


I believe you're getting an error because href is not initially defined in your link. If you give it a default value initially (e.g. - #), you can change it later with JS.


<a id="downloadLink href="#" >DOWNLOAD</a>. This will fix the problem.


You can change or create the HREF attribute dynamically by using something like this:

document.getElementById('downloadlLink').attributes["href"] = "yourlink";
0

精彩评论

暂无评论...
验证码 换一张
取 消