首页 > 解决方案 > 基于 GET 参数的动态 href

问题描述

我想在 HTML 中创建一个链接,其href更改基于 GET 参数(示例链接

href我尝试这个

<a href="?url">text</a>

但它不起作用


这是它应该如何工作的 GIF

对不起我的英语不好

标签: htmlparametersgetparameter-passinghref

解决方案


I understand that you're trying to fill out the "href"-attribute of an anchorlink, by dynamically getting an URL from the GET parameter.

This can be done with the help of JavaScript. I found an example in another Stack Overflow question and made it fit your use case. In that same thread you'll find some good examples of other ways to do it as well.

Try out the following snippet:

   <a id="myLink" href="">Text</a>

   <script>
      const urlParams = new URLSearchParams(window.location.search);
      const myParam = urlParams.get('link');
      const myLink = document.getElementById('myLink');

      if(myParam) {
         myLink.href = myParam; /* The URL given as a parameter */
      } else {
         myLink.href = '#0'; /* If no parameter, the link leads nowhere */
      }
   </script>

推荐阅读