使用 JavaScript 变量填充 HTML 标签

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

Populate HTML Label with JavaScript Variable

javascripthtml

提问by ItalianStallion

I have a simple HTML page where I am trying to populate a label with a JavaScript variable

我有一个简单的 HTML 页面,我试图在其中使用 JavaScript 变量填充标签

<html>
<body onload="loading();">
      <div>
          <h4>Main Page</h4>
          <label id="cookie1" style="color: #0026ff"/> 
<!--MORE CODE-->
      </div>
</body>
</html>

My Javascript function is shown below. It will not populate the label on the html page but if I change the label to a textfield it will work (but i want a label). I have also used 'innerhtml' which does populate the label but it ONLY shows this label. I have more fields and buttons that are erased or hidden if i use 'innerhtml'. Is there something I am missing?

我的 Javascript 函数如下所示。它不会填充 html 页面上的标签,但如果我将标签更改为文本字段,它将起作用(但我想要一个标签)。我还使用了“innerhtml”,它确实填充了标签,但它只显示了这个标签。如果我使用“innerhtml”,我有更多的字段和按钮会被擦除或隐藏。有什么我想念的吗?

function loading() {
    var val1 = "Site:   " + getCookie("storeSite");
    document.getElementById("cookie1").value = val1;
}

回答by gpojd

You are setting the value. Try to set the innerHTML.

您正在设置该值。尝试设置innerHTML。

document.getElementById("cookie1").innerHTML = val1;

A similar JSFiddle.

一个类似的 JSFiddle。

回答by V31

This line in your function

您函数中的这一行

document.getElementById("cookie1").value = val1;

Should have been

本来应该

 document.getElementById("cookie1").innerHTML = val1;