简体   繁体   English

<a>单击指向外部站点的链接时,</a>如何将当前 url 参数添加到 an 的 href

[英]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.

相关问题 如何禁用 href 链接上的“/”预设,以便在单击按钮时不会将完整的外部 URL 添加到站点链接? - How can I disable the “/” preset on a href link so that it does not add a full external URL to the site link when button is clicked? 单击标签a时如何向href URL添加参数? - How can add parameters to href url when click on tag a? 在phonegap中单击href链接时,如何通过url传递参数? - How can i pass parameter via url while clicking href link in phonegap? 如何使用.attr(“href”)前面的参数添加当前网址? - How to add current url with parameters infront of .attr(“href”)? 如何使用Angular挂钩点击链接,并在点击完成之前添加href? - How can I use Angular to hook into clicking a link, and add the href before the click completes? 如何使用URL参数更改页面上的链接href? - How do I use URL parameters to change link href on page? 单击外部链接时的警告以及如何将其添加到链接类 - Warning when clicking external links and how to add it to a link class 替换外部页面中的href / add属性,使其与当前网址相关 - Replace href/add attribute in external page to be relevant to current url 在href链接中传递URL参数 - Passing URL Parameters in href Link 如何在JSON脚本中添加链接/ href /超链接 - How can I add a link/href/hyperlink in JSON script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM