【问题标题】:How to display the value of a javascript variable in html? [closed]如何在 html 中显示 javascript 变量的值? [关闭]
【发布时间】:2023-03-28 21:03:01
【问题描述】:

我想显示单击“Go”按钮时输入的输入值。 输入值存储在名为“value”的变量中,并在 id="show" 中可见。

<html>
<head>
</head>

<body>

<div>
<input type="text" id="input" />
<button onclick="go()">Click</button>
</div>

<div id="show" style="display: none;">
<p>${value}</p>
</div>

<script>


function go() {
    document.getElementById('show').style.display = "block";
   let value = document.getElementById('input').value;
}
</script>
</body>

</html>

【问题讨论】:

标签: javascript html


【解决方案1】:

您只需将要显示的元素的.textContent 设置为变量。不需要隐藏/显示元素,因为元素的 .textContent 最初是空的(因此它最初不会显示任何内容)。

<html>
<head>
  <title>Using form data in the page</title>
</head>
<body>
  <div>
    <input type="text" id="input">
    <button onclick="go()">Click</button>
  </div>

  <div id="show"></div>

  <script>
    function go() {
      let value = document.getElementById('input').value;
      document.getElementById('show').textContent = value;
    }
  </script>
</body>
</html>

【讨论】:

  • 你更改了 HTML - 不过我没有投反对票
  • @mplungjan 我取出了一个多余的元素。它不会改变答案。
  • 确实如此。您不再更新 P
  • @Aditya 确实如此,但没有人知道这一点,并且 SO 规则/政策开始生效。不过,你得到了答案,这对你来说比反对票更重要。
  • @Aditya 不要让它让你失望。随着您获得 Stack Overflow 的经验,您将了解如何编写更好的问题。但是,就目前而言,read this.
【解决方案2】:
  • 使用 type="button"
  • 使用值更新 P 并且不进行隐藏和不显眼的事件处理:

document.querySelector("#go").onclick=function() {
  document.querySelector('#show>p').textContent = document.getElementById('input').value;
}
<div>
  <input type="text" id="input" />
  <button type="button" id="go">Click</button>
</div>

<div id="show">
  <p></p>
</div>

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2015-08-06
    相关资源
    最近更新 更多