簡體   English   中英

如何單擊按鈕以將值添加到數組並顯示它

[英]How to click a button to add a value to an array and display it

我目前堅持嘗試使用onclick按鈕將值推入數組。

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

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

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

})

我試圖在按下按鈕時將1推入數組,然后顯示它。 但是,我當前的代碼無法推送該功能。

它確實可以工作,但是顯示結果的行必須在click回調內部。 現在,在單擊發生之前,顯示僅更新一次。

此外,JQuery .on()建議使用“快捷方式”事件方法( .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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM