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.
答案 0 :(得分:0)
如果您只想重定向到新网址,则无需更改元素的href,只需调用window.open(newLink)
即可打开包含指定链接的新标签。如果您想在同一页面上重定向,请使用window.location.href = newLink
。
请注意,您使用var newLink = element.getAttribute('HREF') + ' ' + theValue;
创建了一个无效的网址,您要为该参数添加空格,您需要/
。
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;
}
&#13;
<a href="https://www.w3schools.com" onclick="return getValue(this)">click here</a>
&#13;