如何单击按钮以将值添加到数组并显示它

时间:2019-03-28 21:19:37

标签: javascript jquery

我目前无法尝试使用onclick按钮将值推入数组。

let display = document.getElementById('screen');
let results = [];
display.innerHTML = results[0];

$(document).ready(() => {

  $('.one').click(function() {
    results.push(1);
  });

})

我试图在按下按钮时将1推入数组,然后显示它。但是,我当前的代码无法推送该功能。

1 个答案:

答案 0 :(得分:2)

它确实可以工作,但是显示结果的行必须在click回调内部。 现在,在单击发生之前,显示仅更新一次。

此外,JQuery不久前不建议使用“快捷方式”事件方法(.click()),并建议使用.on()

最后,innerHTML会影响性能和安全性,因此当所讨论的字符串不包含任何HTML时,请勿使用innerHTML。而是使用.textContent。但是,由于您已经在使用JQuery,因此可以使用.text()

// If you are going to use JQuery, then use it.
// Here, we can get the element with an id of "screen"
// into a JQuery wrapped set object very easily.
// Naming the variable that will hold that JQuery object
// with a $ is a standard convention to remind you that 
// the variable holds a JQuery object and not a standard
// DOM object.
let $display = $('#screen');
let results = [];

// And, with JQuery, if you just pass a function directly 
// to JQuery, that function is automatically understood to
// be a document.ready callback
$(() => {
  $('.one').on("click" ,function() {
    results.push(1);
    $display.text(results[0]); // This must be in the callback to show the most up to date information
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="one" value="push">
<div id="screen"></div>