使用变量作为HREF



我想让HREF由JavaScript中的变量集组成,我还需要页面上显示的文本作为变量。在下面的示例中,我想将字符串" http://google.com"分配给变量,我还需要将"我的链接名称"作为变量。我在这里查看了类似的问题,但我看不出是什么解决了这种特殊情况。

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

在下面的示例中,我可以创建一个称为myLinkName的变量,并将其设置为"现在go there"字符串,但是我不知道如何创建变量并将其设置为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>

您必须使用DOM API

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>

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

使用document.write((的使用。您遵循的方法是反对的。如今,JS未进行评估,而只是写入文档。相反,该文档被明确操纵。

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

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

您可以设置像这样的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>

我将创建一个包含您的链接名称和HREF的对象,并且在页面加载上,相应地分配。类似:


window.addEventListener('load', function(){
    var link = {
        name : 'My Link Name',
        href : 'http://google.com' //should use : instead of =
    };
    var myLink = document.getElementByTagName('a')[0]; //You would change this to whatever selector you want.
    myLink.innerText(link.name);
    myLink.setAttribute('href', link.href);
}, true);

语法可能不是完美的。而且,根据您的情况,最好使用服务器端代码来实现此操作。希望这会有所帮助!

您可以通过这样做更改href属性:

<a href="http://google.com" id="link">
  <script type="text/javascript">
    var yourtext = 'Go Here Now';
    var href = 'http://google.com';
    document.getElementById('link').href = myLinkName;
    document.getElementById('link').innerText = yourtext;
</script></a>

通过使用jQuery,我们可以在下面的元素上更新/添加href。

html代码:

<a href="http://www.live.com/" id="linkId">Click Here</a>

jQuery代码:

$("#linkId").attr("href", "http://www.google.com/'");

最新更新