javascript 将用户输入推送到数组

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

Push user input to array

javascript

提问by Linda wolfenden

Hi so yes this is a previous issue i have had, i have hit the books and whent back to basics adjusted a few things but im still having trouble getting the input value to push to the array can some one please help me get my head around this thanks

嗨,是的,这是我以前遇到的一个问题,我读过书,回到基础时调整了一些东西,但我仍然无法将输入值推送到数组,有人可以帮助我解决问题这谢谢

<!DOCTYPE html>
<html>

 <body>
  <script type="text/javascript">
   var number=["1"]
   function myFunction()
   {
    var x=document.getElementById("box");
     number.push=document.getElementById("input").value;
    x.innerHTML=number.join('<br/>'); 
   }
  </script>
 <form>
  <input id="input" type=text>
   <input type=button onclick="myFunction()" value="Add Number"/>
  </form>

 <div id="box"; style="border:1px solid black;width:150px;height:150px;overflow:auto"> 
  </div>
</body>
</html>

回答by mbinette

Here is the mistake:

这是错误:

number.push(document.getElementById("input").value);

pushis a method, not an attribute ;-)

push是一个方法,而不是一个属性;-)

JSFiddle

JSFiddle

PS:Why the ;after id="box";? You should fix that too..! ;-)

PS:为什么是;之后id="box";?你也应该解决这个问题..!;-)

回答by Bill

You were close, here's the working code:

你很接近,这是工作代码:

<!DOCTYPE html>
<html>

 <body>
  <script type="text/javascript">
   var number = [];

   function myFunction()
   {
     var x = document.getElementById("box");
     number.push(document.getElementById("input").value);
     x.innerHTML = number.join('<br/>'); 
   }
  </script>
 <form>
  <input id="input" type=text>
   <input type=button onclick="myFunction()" value="Add Number"/>
  </form>

 <div id="box" style="border:1px solid black;width:150px;height:150px;overflow:auto"> 
  </div>
</body>
</html>?