简体   繁体   English

将值推入一个空数组?

[英]Pushing values into an empty array?

I'm recently new at programming and JavaScript. 我最近刚接触编程和JavaScript。 I'm not sure why this doesn't work. 我不确定为什么这行不通。 I'm trying to insert numbers into an empty array. 我正在尝试将数字插入一个空数组。 And then have them displayed into the div with the id of "value". 然后将它们显示为div,其ID为“值”。

My JavaScript: 我的JavaScript:

var array = new Array();
// var array = [];

$(document).ready(function() {
  $('#btn').on('click', function() {
    var $input = $('#input').val();
    array.push($input);
  });
  $('#value').text(array);
  console.log(array);
});

My HTML: 我的HTML:

<div id="number">
  <input type="text" id="input">
  <button id="btn"> Submit </button>
</div>

You render the empty array once, when the document is ready. 准备好文档后,只需渲染一次空数组。 Adding more items to the array doesn't rerender the DOM with the new items. 向数组中添加更多项不会重新渲染具有新项的DOM。 You need to update the DOM on each click by moving $('#value').text(array); 您需要通过移动$('#value').text(array);每次点击来更新DOM $('#value').text(array); into the click event handler: 进入click事件处理程序:

 var array = new Array(); // var array = []; $(document).ready(function() { var $input = $('#input'); var $value = $('#value'); $('#btn').on('click', function() { var val = $input.val(); array.push(val); $value.text(array); console.log(array); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="input"> <button id="btn">Add</button> <div id="value"></div> 

Just a reminder that Input Fields supply a String not an Integer. 提醒您,输入字段提供的是字符串而不是整数。

Take a look: 看一看:

 var myArray = []; $(function() { $('#btn').on('click', function() { var $input = $('#input').val(); myArray.push(parseInt($input)); console.log(myArray) $('#value').text("[" + myArray.join(", ") + "]"); }); }); 
 .input { padding: 10px; font-family: Arial, Helvetica, sans-serif; font-size: 1em; } .input input { width: 60px; height: 1.25em; } .input button { padding: .25em .6em; } .output { font-family: Arial, Helvetica, sans-serif; font-size: 1em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="input"> <input type="number" id="input" /> <button id="btn">Add</button> </div> <div class="output"> <div id="value"></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM