简体   繁体   中英

How do I use URL parameters to change link href on page?

I would like to change the href value of a link using URL parameters.

Example:

Default <a id="dlink" href="link-1">LINK</a>

But, when the user goes something like this https://url.com/?dlink=link-2

It swaps out the link

New Link <a id="dlink" href="link-2">LINK</a>

First you need to get value from url. If you're not using some javascript framework you can create a function for it using jquery.

Please check Get url parameter jquery Or How to Get Query String Values In js for it.

After that, get element "a" by ID and set the value there.

$("#dlink").attr("href", hrefFromParam);

Refer to this function to get URL parameters: Get url parameter jquery Or How to Get Query String Values In js

And with jQuery you can set the href attribute of your <a>

$('#dlink').attr('href', $.urlParam('dlink'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM