【问题标题】:Appending current URL parameters onto anchor link将当前 URL 参数附加到锚链接上
【发布时间】:2021-09-19 05:04:50
【问题描述】:

在类似的页面

https://www.example.com/?firstname=Steven&lastname=Smith&email=steve%40gmail.com&phone=0404555555

我有一个链接到https://www.example.com/form 的按钮(锚链接)#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell

我想将当前 URL 中的 URL 参数附加到按钮的 URL,以便按钮的 href 现在是 https://www.example.com/form/?firstname=Steven&lastname=Doig&email=steve%40gmail.com&phone=0404555555

请问如何用 JavaScript 做到这一点?

【问题讨论】:

标签: javascript


【解决方案1】:

使用window.location.search:

var url = "https://exmaple.com";
var newurl = url + window.location.search;

newurl 将包含所有get(例如?something=something&something2=something5)数据。

要更改ahref

var button = document.getElementById('#ptsBlock_553944');
button.href = button.href + window.location.search;

【讨论】:

  • 谢谢。如何将按钮的 href 值设置为 newurl
  • 它是button 还是a 元素?如果是按钮,是表单提交按钮吗?
  • 这是一个a 元素
  • 编辑了我的答案
【解决方案2】:

如果您不关心支持旧版浏览器,可以使用URL APIURLSearchParams

function appendCurrentUrlSearchParams(anchorElement) {
  const currUrlSearchParams = new URL(window.location.href).searchParams;
  const link = new URL(anchorElement.href);

  // uncomment this line if you want to clear query parameters already present in the anchor url
  // link.search = '';

  for (const entry of currUrlSearchParams.entries()) {
    link.searchParams.append(entry[ 0 ], entry[ 1 ]);
  }
  
  anchorElement.href = link.href;
}

在您的情况下的用法:

appendCurrentUrlSearchParams(document.querySelector('#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell'));

【讨论】:

  • 我给它+1 因为它可以在已经有一些GET 参数的情况下工作 - 这不是 OPs 问题的最简单解决方案(不是这种情况)但有人可能需要这个
【解决方案3】:

阅读Html select using select to change the link of a button with Javascript

特别是关于

的部分
  1. 使用类似 document.getElement MDN getElement Link 的方式获取元素

  2. 将该元素的 .href 更改为您想要的。

function selectFunction() {
    var x = document.getElementById("selectopt").value;

    document.getElementById("mylink").innerHTML = x;
  
    document.getElementById("mylink").href = "http://www." + x + ".com";
  
}
document.location.pathname = '/questions/69240453/appending- 
current-url-parameters-onto-anchor-link/69240510';

//get the document pathname I chose from document.location
let data = document.location.pathname;

let preUrlString = 'www.example.com/form';

let newString = preUrlString + data;

console.log(newString);
'www.example.com/form/questions/69240453/appending- 
current-url-parameters-onto-anchor-link/69240510'

document.getElementById("mylink").href = newString;

【讨论】:

  • 谢谢。如何插入 URL 参数?
  • @Steve 有足够的意义吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 2019-06-22
相关资源
最近更新 更多