JavaScript生成多语言切换链接时出现拼接错误的问题求助
问题分析与修复方案
问题原因
你生成的链接出现错误拼接,核心原因是给<a>的href赋值的是相对路径格式的字符串(比如fr.example.com/),浏览器会默认将其当作当前域名下的相对资源,自动拼接到当前页面的完整URL后面,最终导致https://example.com/https://fr.example.com/这类错误格式。
修复代码
只需要修改JavaScript部分,生成包含协议的完整绝对URL即可:
let protocol = window.location.protocol; // 获取当前协议(http:// 或 https://) let hostName = window.location.hostname; let pathName = window.location.pathname; let frUrl = protocol + '//fr.' + hostName + pathName; // 拼接完整绝对路径 var a = document.createElement('a'); var linkText = document.createTextNode("FR"); a.appendChild(linkText); a.href = frUrl; // 可选:添加rel属性控制跳转时的referrer行为 a.rel = "nofollow noreferrer"; let dropDownContent = document.querySelector(".dropdown-content"); dropDownContent.appendChild(a);
关键修改点
- 新增
window.location.protocol获取当前页面的协议,确保生成的是完整的绝对URL,而非相对路径 - 拼接后的URL直接赋值给
a.href,浏览器会识别为独立子域名的外部链接,不会再与当前域名错误拼接
完整代码示例
HTML
<div class="dropdown"> <div class="dropbtn">EN</div> <div class="dropdown-content"> </div> </div>
CSS
.dropdown { position: relative; display: inline-block; } .dropbtn { padding: 5px; cursor: pointer; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; width: 140px; } .dropbtn { width: 40px; } .dropbtn::after { background: rgba(0, 0, 0, 0) url("https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_down_48px-16.png") no-repeat scroll center center; content: ""; height: 16px; position: absolute; right: 0; top: 7px; width: 16px; } .dropdown-content a { color: black; padding: 2px 0 2px 5px; text-decoration: none; display: block; } .dropdown:hover .dropdown-content { display: block; }
内容的提问来源于stack exchange,提问作者user9671171
相关产品推荐
相关产品推荐

