【问题标题】:Putting Javascript variable in html link将 Javascript 变量放入 html 链接
【发布时间】:2014-08-21 06:46:10
【问题描述】:

我有一个动态变量,该变量由脚本中的网页用户更新,当用户单击超链接时,我需要能够将该变量发送到另一个网页。所以我需要类似的东西

<a href="http://example.com?variable=variableGetter()">Link</a>

工作,但我不确定如何执行此操作的确切语法。我的 JavaScript 中已经有一个 getter,我只需要在用户单击链接时能够访问它。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    您可以使用 onclick 操作将您转到为您导航页面的功能。

    或者

    您可以在需要更改变量值的任何时候更新 href 属性。

    第二个选项可能更可取,但这在很大程度上取决于页面中的其他内容以及变量的设置方式

    【讨论】:

      【解决方案2】:

      这看起来很熟悉:

      How to redirect on another page and pass parameter in url from table?

      <a href="#" id="redirectwithid">link</a>
      

      原生 JS:

      document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter());
      

      jQuery:

      $("#redirectwithid").click(function() {
         var yourVariable = variableGetter();
         if (yourVariable != null) {
            window.location = 'yoururl?variable=' + yourVariable;
         }
      });​
      

      为原生 JS 添加: 我不知道你的代码,所以只需在你想要更新变量的地方插入代码 - 同时 href 会改变。

      编辑:

      如果您想添加多个变量,例如 ?variable=1 和第二个 variable2=2,您可以通过在变量之间添加 & 来实现,如下所示:

      NativeJS:

      document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter() + '&variable2=' + variable2Getter());
      

      JQuery:

      $("#redirectwithid").click(function() {
         var yourVariable = variableGetter();
         var yourVariableTwo = variableTwoGetter();
         if (yourVariable != null) {
            window.location = 'yoururl?variable=' + yourVariable + '&' + yourVariableTwo;
         }
      });​
      

      【讨论】:

      • 添加了 nativ JS 作为解决方案 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      相关资源
      最近更新 更多