简体   繁体   English

我想将一个值推送到一个数组然后发出警报,但什么都没有显示?

[英]I wanna push a value to an array and then alert, but nothing is not shown?

I wrote this block code to get some value and alert that.我编写了这个块代码来获得一些价值并提醒它。 but in alert window nothing is shown.但在警报 window 中没有显示任何内容。 I realized that I can move the "inputValue" variable into the function to fix that problem, but I don't know why?我意识到我可以将“inputValue”变量移动到 function 来解决这个问题,但我不知道为什么?

JavaScript: JavaScript:

let array = [];
let textInput = document.getElementById('textInput');
let button = document.getElementById('button'); 

let inputValue = textInput.value;

function push(){
    alert(inputValue);
}


button.addEventListener('click' , push);

HTML Code section: HTML 代码部分:

    <input type="text" id="textInput">
    <input type="button" id="button" value="push to array">

It is because when the site is loaded then it will grab the input fields value and at this time it is empty.这是因为当网站被加载时,它会抓取输入字段的值,此时它是空的。

You have to grab the input value when the button gets clicked.单击按钮时,您必须获取输入值。 So put the part所以把部分

let inputValue = textInput.value;

Inside your push() method which gets invoked on button click and it will work.在按钮单击时调用的push()方法内部,它将起作用。 The snippet below demonstrates it.下面的代码片段演示了它。

 let array = []; let textInput = document.getElementById('textInput'); let button = document.getElementById('button'); function push() { let inputValue = textInput.value; alert(inputValue); } button.addEventListener('click', push);
 <input type="text" id="textInput"> <input type="button" id="button" value="push to array">

You could re-write your snippet like in the following example.您可以像以下示例一样重新编写代码段。 textInput should be a const and inside push function just use textInput.value . textInput应该是一个const并且内部push function 只需使用textInput.value

 let array = []; const textInput = document.getElementById('textInput'); const button = document.getElementById('button'); function push() { alert(textInput.value); } button.addEventListener('click', push);
 <input type="text" id="textInput"> <input type="button" id="button" value="push to array">

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

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