Javascript 设置一个 JS 变量并在 html 标签中使用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13806621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:49:18  来源:igfitidea点击:

Setting a JS variable and using it in html tag

javascripthtmlvariablesvar

提问by treasureireland

I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, this is the code:

我已经设置了一个变量,我需要将这个变量拉入一个 html 元素中,但我无法让它打印出值,这是代码:

<script>
    var randomnumber=Math.floor(Math.random()*11)
</script>

<div id="<script type="text/javascript">document.write(randomnumber)</script>"></div>

Thanks.

谢谢。

Edit: I just used a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?

编辑:我只是以 div 为例,但我需要向 img 标签添加一个随机数,因为它用于跟踪标签,并且需要一个唯一标识符。有没有更好的方法来解决这个问题?

回答by Juan Mendes

Use

<script>
document.write('<div id="'+randomnumber+'" ></div>');
</script>

You can't open a script tag inside an attribute

您无法在属性内打开脚本标记

回答by Viren Rajput

Or you can create it using JS:

或者您可以使用JS以下方法创建它:

var randomnumber=Math.floor(Math.random()*11);
a = document.createElement('div');
a.setAttribute('id',randomnumber);
document.body.appendChild(a);

// if you know the exact class or ID where it is to be appended you can use

document.getElementsByClassName("myclass")[0].insertBefore(a, document.getElementsByClassName("beforeClass").firstChild);

This will create a div, with the idas the randomnumberand append it to the body

这将创建一个div,id作为randomnumber并将其附加到body