我想这会很简单,但我还没有找到答案。如何使所有class="namehere"的span元素都显示在输入文本中插入的内容?

function start() {
  var name = document.getElementById("name").value;
  document.getElementByClassName("namehere").innerHTML = name;
}

<input id="name" type="text" value="Type name here">
<button type="button" onclick="start()">start</button>
<br>
<br>
<span class="namehere"></span> is doing this and that.
<br>
<span class="namehere"></span> wants to do this and that.
<br>
<span class="namehere"></span> is not doing this or that.
<br>
<span class="namehere"></span> wants to do this but instead is doing that.

最佳答案

看看jQuery,它会在这类解决方案中为您提供很多帮助。
您需要在标题中包含<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>,并将代码更改为:

<!DOCTYPE html>
<html>
  <head>
   <title>test</title>
   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  </head>
  <body>
    <input id="name" type="text" value="Type name here">
    <button type="button" onclick="start()">start</button>
    <br>
    <br>
    <span class="namehere"></span> is doing this and that.
    <br>
    <span class="namehere"></span> wants to do this and that.
    <br>
    <span class="namehere"></span> is not doing this or that.
    <br>
    <span class="namehere"></span> wants to do this but instead is doing that.
    <script>
     function start(){
         var name = $("#name").val();
          $(".namehere").text(name);
     }
    </script>
  </body>
</html>

10-05 21:00
查看更多