【问题标题】:How can I change value of html element based off of user's input?如何根据用户的输入更改 html 元素的值?
【发布时间】:2019-12-11 14:27:33
【问题描述】:

如第 22 行所示的列表项,默认为“panthers 20”。根据用户的一些输入,我试图将“黑豹”覆盖到用户输入的任何内容。

我熟悉java/c#/c++。但是web开发对我来说很新,所以我似乎对语法缺乏了解。

我已经尝试通过阅读教程来解决这个问题,但是我尝试过的所有不同的语法组合都不起作用。

<!DOCTYPE html>
<html>
  <head>
    <script> //used when user enters in value and submits
      function showInput() {
          document.getElementById('display').innerHTML =
                      document.getElementById("user_input").value;
      }
    </script>
  </head>
<body>
  <form>
    <label><b>Enter a Message</b></label>
    <input type="text" name="message" id="user_input">
  </form>

  <input type="submit" onclick="showInput();"><br/>
  <label>Your input: </label>
  <p><span id="display"></span></p>


  <li class="team"><span id="lbltipAddedComment">panthers</span><span class="score">20</span></li>


  <script> //attempting to change the value of panthers to the users input
  document.getElementById("lbltipAddedComment").innerHTML = display.value;
  </script>

</body>
</html>

如果用户输入 rams,列表项“team”应该说 rams 20,而不是 panthers 20。

document.getElementById("lbltipAddedComment").innerHTML = display.value;

似乎是问题所在。使用display.value 输出undefined20 并使用display 输出[object HTMLSpanElement]20

【问题讨论】:

  • "display" 不是输入元素。如果你想获取非输入元素的值,你必须使用innerHTML。尝试使用“display.innerHTML

标签: javascript html


【解决方案1】:

确保将操作 DOM 的 javascript 代码放在 HTML 文件的底部。这样 DOM 可以先加载,然后 javascript 才能生效。

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <form>
    <label><b>Enter a Message</b></label>
    <input type="text" name="message" id="user_input">
  </form>

  <input type="submit" onclick="showInput();"><br/>
  <label>Your input: </label>
  <p><span id="output-section"></span></p>


  <li class="team"><span id="lbltipAddedComment">panthers</span> <span class="score">20</span></li>


  <script>
    //attempting to change the value of panthers to the users input
    function showInput() {
      var userInput = document.getElementById("user_input").value;
      document.getElementById('output-section').innerHTML = userInput;
      document.getElementById("lbltipAddedComment").innerHTML = userInput;
    }
  </script>

</body>

</html>

【讨论】:

  • @tonytone 没问题!如果您对此答案感到满意,请单击投票按钮下方的复选标记以接受它。
  • 啊好吧,第一次发帖
猜你喜欢
  • 1970-01-01
  • 2014-03-18
  • 2015-11-02
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2014-09-13
  • 1970-01-01
相关资源
最近更新 更多