简体   繁体   English

如何用 JavaScript 或 jQuery 替换当前 URL 的部分链接?

[英]How to replace part of the a link to the current URL by JavaScript or with jQuery?

I've got a link that exists on many pages, which I would like to use JavaScript to make the later part of the link to be changed according to the current url * of the visiting page.我有一个存在于许多页面上的链接,我想使用 JavaScript 使链接的后面部分根据访问页面的当前 url * 进行更改。

(* current url mentioned here = the current web address appears on the browser's address bar) (* 这里提到的当前url = 当前 web 地址出现在浏览器的地址栏上)

What is the right way to change URL after ?redirect= to the current visiting URL using JavaScript??redirect=之后使用 JavaScript 将 URL 更改为当前访问的 URL 的正确方法是什么?

For example, this is the original:例如,这是原来的:

<a href="https://app.example.com/?redirect=www.example.com">Link</a>

Now, the current url is https://www.example.com/game?q=123 , the desired result would be:现在,当前 url 是https://www.example.com/game?q=123 ,期望的结果是:

<a href="https://app.example.com/?redirect=https://www.example.com/game?q=123">Link</a>

Thanks a lot非常感谢

Trying to learn from these posts, but was not successful yet...尝试从这些帖子中学习,但尚未成功...
how to replace part of the URL with JavaScript? 如何用 JavaScript 替换部分 URL?
Get the current URL with JavaScript? 获取当前的 URL 和 JavaScript?
Replace a part of the current URL 更换部分现行URL

What I would do is get the href attribute from all anchor links.我要做的是从所有锚链接中获取href属性。 Create a new URL() object so you can work the url parameters.创建一个新的URL() object 以便您可以使用 url 参数。 Replace the value and finally replace the href attribute with the result.替换值,最后用结果替换href属性。

For example (explanation in comments):例如(评论中的解释):

 // Make sure the document is loaded before you start working with it document.addEventListener("DOMContentLoaded", function(e){ // Get all anchor links present in the document and loop through them document.querySelectorAll("a").forEach(function(element){ // Get the value of the href attribute const url_str = element.getAttribute("href"); // Create a new URL object so we can work with it const url = new URL(url_str); // Check if the anchor tag should be affected or not if(url.searchParams.get('redirect')) { // Get the current url from the browser const current_url = window.location.href; // Set the redirect parameter to the value of current_url const redirect = url.searchParams.set("redirect", current_url); // Replace the href attribute with the new url element.setAttribute("href", url.href); // This is just to show it working. You can remove this. console.log(element.getAttribute("href")); } }); });
 <a href="https://app.example.com/?redirect=www.example.com">Link</a> <a href="https://app.example.com/?redirect=www.different.com">Link</a> <a href="https://app.example.com/">Link</a>

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

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