单击 link 到外部站点时,如何将当前 url 参数添加到 <a> 的 href
How can I add the current url parameters to the href of an <a> when clicking link to external site
我们使用 instapage 作为登录页面的工具,如果用户点击带有外部 links 的标签,它们会从 links 中删除 url 参数。不过我想保留 location.search。
我尝试在此处使用此脚本,但它根本不起作用 - 因为,除非在 href link.
中指定,否则参数仍会被删除
window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + window.location.search;
e.preventDefault();
}
});
我在这里明显遗漏了什么吗?
我通过在页面加载时修改 hrefs 而不是尝试添加 onClick 参数来解决这个问题。这是代码 - 也尊重其中已经有参数的网址。
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)
}
})
});
我们使用 instapage 作为登录页面的工具,如果用户点击带有外部 links 的标签,它们会从 links 中删除 url 参数。不过我想保留 location.search。
我尝试在此处使用此脚本,但它根本不起作用 - 因为,除非在 href link.
中指定,否则参数仍会被删除window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + window.location.search;
e.preventDefault();
}
});
我在这里明显遗漏了什么吗?
我通过在页面加载时修改 hrefs 而不是尝试添加 onClick 参数来解决这个问题。这是代码 - 也尊重其中已经有参数的网址。
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)
}
})
});