简体   繁体   English

如何在 html 标签内插入 javascript 变量<a href>?</a>

[英]How to insert a javascript variable inside an <a href> html tag?

I want to insert a javascript variable inside an html link such that each time the value of the variable is changed, it changes immediately in the html link.我想在 html 链接中插入一个 javascript 变量,这样每次更改变量的值时,它都会在 html 链接中立即更改。

I have tried already many possiblities but unsuccesfull.My code is as follows:我已经尝试了很多可能性,但没有成功。我的代码如下:

<head>
  <title>Hello World</title>
</head>
<body>

CATEGORIE NAME: <input id="first_name">
DEVICE NAME: <input id="last_name">
<button id="say">Send!</button>

<hr>
<div id="result"></div>

<script>
function say_hi() {
    var fname = document.getElementById('first_name').value;
    var lname = document.getElementById('last_name').value;

    var html = 'CODE: <b>' + fname  + lname;

    document.getElementById('result').innerHTML = html;
}

document.getElementById('say').addEventListener('click', say_hi);


</script>
    <a href="http://barcodes4.me/barcode/c39/ +$html.png">Click this link</a>

</body>
</html>

Please what should i so so that the link takes directly each time the value of the variable "html" and adds in as part of the link请问我应该怎么做,以便链接每次都直接获取变量“html”的值并作为链接的一部分添加

The DOM API is fairly simple. DOM API 相当简单。 It follows almost exactly the same convention as the HTML.它遵循与 HTML 几乎完全相同的约定。 For example, the href attribute of the a tag is the href property of the a object.例如, a标签的href属性是a object 的href属性。

What you need to do is make your a tag easier to find:您需要做的是让您a标签更容易找到:

<a id="this_link" href="">Click this link</a>

Now in your script you can simply do:现在在您的脚本中,您可以简单地执行以下操作:

var link = document.getElementById('this_link');
link.href = "http://barcodes4.me/barcode/c39/" + html + ".png"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM