[英]How can I add the current url parameters to the href of an <a> when clicking link to external site
we use instapage as a tool for landing pages and they strip url parameters from links if users click on tags with external links.我们使用 instapage 作为登陆页面的工具,如果用户点击带有外部链接的标签,它们会从链接中删除 url 参数。 I want to preserve the location.search though.
不过,我想保留 location.search 。
I tried using this script here, but it doesn't work at all - as in, the parameters still get removed unless they are specified in the href link.我在这里尝试使用这个脚本,但它根本不起作用 - 除非在 href 链接中指定参数,否则参数仍然会被删除。
window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + window.location.search;
e.preventDefault();
}
});
Anything obvious I am missing here?我在这里遗漏了什么明显的东西吗?
I solved the issue by just modifying the hrefs on page load instead of trying to add the parameters onClick.我通过修改页面加载时的hrefs而不是尝试添加参数onClick来解决了这个问题。 Here is the code - also respecting urls that already have parameters in them.
这是代码 - 也尊重其中已经有参数的 url。
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelectorAll('[href^="http"]').forEach((element) => {
var hrefString = element.getAttribute('href')
if(hrefString.includes('?')) {
element.setAttribute('href', hrefString + window.location.search.replace('?', '&') )
} else {
element.setAttribute('href', hrefString + window.location.search)
}
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.