简体   繁体   中英

Dynamicaly changing HREF attribute in <A> tag

I am working on a website now. The code is supposed to be very portable and run on different platforms. I need to change the HREF attribute dynamically in my <a> tag.
My code is looking like:

 function getValue(element) { var theValue = prompt('Please enter the value for the link: ' + element.getAttribute('HREF'), '0'); if (theValue == null) { return false; } var newLink = element.getAttribute('HREF') + ' ' + theValue; element.setAttribute('HREF', newLink); // test what I set: prompt(newLink); return true; } 
 <A HREF="https://www.w3schools.com" ONCLICK="return getValue(this)">click here</A> 

If the visitor clicks on "click me" link on my website, a prompt window will be shown. If the user will enter the wished value, a website with the URL will open: https://www.w3schools.com theValue has to be opened.

Right now, nothing happens. Thank's a lot!

I need to clarify couple thinks. This example is very simplified. My website is exporting links from engine for internal usage. There is no security issue to fake links. The website consists of 1.000 links as is www.w3schools.com. It is no way to put some static IDs for <a> tags. There is no way to create some forms. This is not good solution to have links with matching edit boxes and buttons to post.

The best solution could be to click on link, enter value in the prompt window and redirect URL as is mentioned. Thanks to Gil for review. Now I see that the code works in IE, but it does not work in Mozilla browser.

If you only want to redirect to the new URL you don't need to change the href of the element, just call window.open(newLink) and it will open a new tab with the specified link. If you want to redirect on the same page then use window.location.href = newLink .

Note that you were creating an invalid URL with var newLink = element.getAttribute('HREF') + ' ' + theValue; you were adding the parameter with a space, you need a / .

 function getValue(element) { var theValue = prompt('Please enter the value for the link: ' + element.getAttribute('href'), '0'); if (theValue == null) { return false; } var newLink = element.getAttribute('href') + '/' + theValue; window.open(newLink); return true; } 
 <a href="https://www.w3schools.com" onclick="return getValue(this)">click here</a> 

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