如何从javascript中的输入中获取值?

时间:2018-02-17 07:49:58

标签: javascript html

如何从javascript中的输入元素中获取值?由于某种原因,我的代码没有执行。这是我的HTML代码:

   <section id ="my-life" style="margin-left:39em;">

   <input class="jenny" placeholder="Your First Name"/> <br /><br />

   <button id="get">Subscribe</button>

   <br /><br />

  <div id ="whitelion">Thank You!</div>



    This is my javascript code:

   function buttonClicked() {
   var Niche = document.getElementsByClassName("jenny");
   var results = document.getElementById("whitelion");


   results.innerHTML = "Hello" + Niche[0].value;

}

3 个答案:

答案 0 :(得分:2)

function buttonClicked() {
  var Niche = document.getElementsByClassName("jenny");
  var results = document.getElementById("whitelion");
  results.innerHTML = "Hello " + Niche[0].value;
}
<input class="jenny" placeholder="Your First Name"/>
<br /><br />
<button onclick='buttonClicked();'>Subscribe</button>
<br /><br />
<div id ="whitelion">Thank You!</div>

答案 1 :(得分:1)

  <section id ="my-life" style="margin-left:39em;">

   <input class="jenny" placeholder="Your First Name"/> <br /><br />

   <button id="get">Subscribe</button>

   <br /><br />

  <div id ="whitelion">Thank You!</div>



<script>
   function buttonClicked() {
     var Niche = document.getElementsByClassName("jenny");
     var results = document.getElementById("whitelion");

     results.innerHTML = "Hello" + Niche[0].value;
   }

  document.getElementById('get').onclick = buttonClicked;

</script>

答案 2 :(得分:1)

我在编辑器上尝试了你的代码。它工作正常。但是您必须在<script>元素中包含JS代码。并将其放在文档的底部。

function buttonClicked() {
   var Niche = document.getElementsByClassName("jenny");
   var results = document.getElementById("whitelion");


   results.innerHTML = "Hello " + Niche[0].value;
}
<section id ="my-life">

   <input class="jenny" placeholder="Your First Name"/> <br /><br />

   <button id="get" onclick="buttonClicked()">Subscribe</button>

   <br /><br />

  <div id ="whitelion">Thank You!</div>
  <br/>
  </section>