繁体   English   中英

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

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

我有一个存在于许多页面上的链接,我想使用 JavaScript 使链接的后面部分根据访问页面的当前 url * 进行更改。

(* 这里提到的当前url = 当前 web 地址出现在浏览器的地址栏上)

?redirect=之后使用 JavaScript 将 URL 更改为当前访问的 URL 的正确方法是什么?

例如,这是原来的:

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

现在,当前 url 是https://www.example.com/game?q=123 ,期望的结果是:

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

非常感谢

尝试从这些帖子中学习,但尚未成功...
如何用 JavaScript 替换部分 URL?
获取当前的 URL 和 JavaScript?
更换部分现行URL

我要做的是从所有锚链接中获取href属性。 创建一个新的URL() object 以便您可以使用 url 参数。 替换值,最后用结果替换href属性。

例如(评论中的解释):

 // 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