首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用变量作为href

使用变量作为href
EN

Stack Overflow用户
提问于 2019-05-09 00:53:54
回答 6查看 471关注 0票数 0

我希望href由一个在javascript中设置的变量组成,我还需要在页面上显示的文本是一个变量。在下面的例子中,我希望将字符串"http://google.com“赋给一个变量,我也需要有”我的链接名称“作为变量。我在这里看过类似的问题,但我看不出是什么解决了这种特殊情况。

  <a href="http://google.com">Go Here Now</a><br>

在下面的示例中,我可以创建一个名为myLinkName的变量并将其设置为字符串"Go here now“,但是我不知道如何创建一个变量并将其设置为href的值,例如"http://google.com

<script type="text/javascript">
   var myLinkName = "Go Here Now";
</script>

<a href="http://google.com">
  <script type="text/javascript">
    document.write(myLinkName)
  </script></a>
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2019-05-09 01:17:32

我担心您正在使用一些非常古老的JavaScript材料。

描述了document.write()的用法。您正在遵循的方法是过时的。今天,JS没有被评估,只是被写入到文档中。相反,文档是显式操作的。

首先:<script>足以声明一些JavaScript。不再需要type属性。

<a id=myLink></a>
<script>
//get a reference to the a element
const myLink = document.getElementById("myLink");

//set the text
myLink.innerText = "Click me!";

//set href
myLink.href = "http://google.com";
</script>
票数 1
EN

Stack Overflow用户

发布于 2019-05-09 01:02:36

您必须使用DOM

HTML

<a id="aLink"></a>

Javascript

let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is my Link'

完整的代码:

<html>
  <body>
    <a id="aLink"></a>

    <script>
      let link = document.getElementById('aLink');
      link.href = "https://google.com";
      link.innerText = 'This is Link';
    </script>

  </body>
</html>
票数 5
EN

Stack Overflow用户

发布于 2019-05-09 01:02:13

可以像这样设置href属性

 var text = 'Go Here Now';
    var href = 'http://google.com'
    var atag = document.getElementsByTagName('a')[0];
    atag.innerText = text;
    atag.href = href;

var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
<a href=""></a><br>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56045590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档