如何在 HTML 中显示 Javascript 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15971994/
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-10-27 02:47:13  来源:igfitidea点击:

How can I display a Javascript variable in HTML?

javascripthtmlcss

提问by Tom

I am trying to add some javascript to my HTML document. In my example I would like to display the square of 2 in text with HTML. The result should be calculated using a js script. For example, consider this:

我正在尝试将一些 javascript 添加到我的 HTML 文档中。在我的示例中,我想在 HTML 文本中显示 2 的平方。结果应使用 js 脚本计算。例如,考虑这个:

In my header:

在我的标题中:

<script type="text/javascript">
  var square = 2*2
</script>

In my body:

在我的身体里:

<p>The square of 2 is <span id="square">.</span></p>

What do I have to add to make this work?

我需要添加什么才能完成这项工作?

回答by Schleis

You need to set the innerHtmlof the span to the value so it would be something like this:

您需要将范围的 设置为该innerHtml值,因此它会是这样的:

<script type="text/javascript">
  var square = 2*2;
  document.getElementById('square').innerHTML = square;
</script>

But you will want to move this script to after where the span is written as the page is rendered procedurally and the span doesn't exist yet in the head. The other option is to wrap your code in a document.onloadfunction like:

但是您会希望将此脚本移到写入跨度的位置之后,因为页面是按程序呈现的,并且跨度尚不存在于头部。另一种选择是将您的代码包装在一个document.onload函数中,例如:

<script type="text/javascript">
  document.onload(function() {
      var square = 2*2;
      document.getElementById('square').innerHTML = square;
  });
</script>

回答by KernelPanik

Try using the HTML Document Object Model, for example,

尝试使用 HTML 文档对象模型,例如,

function changeText(){
 var ans = 2*2;
document.getElementById("square").innerHTML = ans;
}

Then, attach this javascript to an event such as

然后,将此 javascript 附加到一个事件,例如

<body onload="changeText()">