繁体   English   中英

从URL获取查询字符串并将其传递给Href

[英]Fetch Query String From URL and Pass It to Href

我在这里看到了几种可能的解决方案,但是以某种方式我找不到合适的解决方案。

我的情况是这样的:

用户进入URL中携带查询字符串的pageA。

看起来像这样: http : //example.com?name=xxxxx&email=xxxxx&a1=1xxxxx

在该页面上,我有两个链接,可以说它们的ID为linkA和linkB。

我对第一个这样的标记感兴趣:

<a href="" id="linkA">Link A</a>

我需要从url提取整个查询字符串,并将其添加到linkA,它将指向另一个URL。 因此,最终链接如下所示:

<a href="http://anotherurl.com?name=xxxxx&email=xxxxx&a1=1xxxxx" id="linkA">Link A</a>

您能帮我解决干净的问题吗?

先感谢您!

您可以只使用window.location.search从页面的URL访问整个查询字符串。 它将返回如下内容: ?name=xxxxx&email=xxxxx&a1=1xxxxx

然后,您可以将其附加到锚元素的href属性,例如

document.querySelector('#linkA').href = `http://anotherurl.com/${window.location.search}`;

如果您需要基于ES5的解决方案,则可以使用:

document.querySelector('#linkA').href = 'http://anotherurl.com/' + window.location.search;

您可以尝试使用window.location的搜索键,它返回当前URL的搜索查询。

因此,在http://example.com/?name=xxxxx&email=xxxxx&a1=1xxxxx上 ,使用以下命令

window.location.search

将为您提供以下字符串

?name=xxxxx&email=xxxxx&a1=1xxxxx

然后,您可以将此字符串附加到第二个锚标记的“ href”

试试下面的代码,它工作正常:

$(document).ready(function(){
    var parameters = window.location.search;
    var link = $('#linkA').attr('href');
    $('#linkA').attr('href', link + parameters);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM