使用javascript更改链接url

使用javascript更改链接url,javascript,Javascript,这是我正在更新的网站的javascript菜单。我想添加一个动态链接(id=IT-link)链接到该网站的意大利版本。但是URL需要根据查看器所在的页面进行更改。有人能告诉我怎么做吗!?我对javascript非常陌生,正在自学。谢谢,加泰罗尼亚 window.onload = uline; var pagename = document.getElementById("TAG").getAttribute("data-name"); function uline() { if (pagen

这是我正在更新的网站的javascript菜单。我想添加一个动态链接(id=IT-link)链接到该网站的意大利版本。但是URL需要根据查看器所在的页面进行更改。有人能告诉我怎么做吗!?我对javascript非常陌生,正在自学。谢谢,加泰罗尼亚

window.onload = uline;

var pagename = document.getElementById("TAG").getAttribute("data-name");

function uline()
{
if (pagename == 'HOME' )
document.getElementById(pagename).style.color="#ffffff";
else
document.getElementById(pagename).style.textDecoration="underline";
}


document.write('<DIV CLASS=RIGHT><B>');

document.write('<a href=\"+link+'\"     id=IT-LINK      >ITALIANO</a>    &nbsp;&nbsp;&nbsp;');
document.write('<br><br>');
document.write('<a href="news.html"     id=NEWSLETTER   >NEWSLETTER</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="prodotti.html" id=PRODUCTS     >PRODUCTS</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="bio.html"      id=BIO          >PHILOSOPHY/BIOG</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="contatti.html" id=CONTACTS     >CONTACTS</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="home.html"     id=HOME         >HOME</a>');

document.write('</B></DIV>');
window.onload=uline;
var pagename=document.getElementById(“标记”).getAttribute(“数据名”);
函数uline()
{
如果(pagename=='HOME')
document.getElementById(pagename).style.color=“#ffffff”;
其他的
document.getElementById(pagename).style.textDecoration=“underline”;
}
文件。写(“”);
文件。写(“”);
文件。写(“

”); 文件。写(“”); 文件。写(“”); 文件。写(“”); 文件。写(“”); 文件。写(“”); 文件。写(“”);
您应该在HTML中添加指向意大利主页的href链接。如果访问者没有启用javascript,这将是最小值。 对于使用javascript的用户,可以执行以下操作:

document.getElementById("IT-LINK").href = getItalianVersionOf(window.location.href);
其中getItalianVersionOf获取页面url并提供此url的意大利版本


请注意,在服务器端这样做(例如使用PHP)会更好。

我真的不明白您将如何找到页面,但我将把这个逻辑留给您。要替换url,可以使用下面的javascript代码

//your logic to find page and corresponding url
    document.getElementById(linkId).setAttribute('href',yourLink);

如果需要更多信息,请告诉我。

谢谢大家的帮助,但我找到了一种更简单的方法。通过将“/it”添加到URL,我获得了一个链接,该链接将我带到当前网页的意大利版本

document.write('<font size=2.5><a href="it/home.html"   id=IT-LINK      >ITALIANO</a></font> &nbsp;&nbsp;&nbsp;');

var newURL = window.location.protocol + "//" + window.location.host + "/it" + window.location.pathname;
document.getElementById("IT-LINK").href = newURL;
document.write(“”);
var newURL=window.location.protocol+“//”+window.location.host+“/it”+window.location.pathname;
document.getElementById(“IT-LINK”).href=newURL;
但是!现在我必须请你帮忙做相反的事情:
我怎样才能从意大利语URL中取出“/it”使我回到英语版本?

完全错了。A) 您不能使用文档。页面加载后写入,b)您需要将赋值从DOM移到onload,函数Urline前面的第一条语句不能放在它的位置。看起来像是重复的。您可以显示标记以及如何设置属性吗?您可能只需要location.pathname.substring(1.split)(“.”[0]