简体   繁体   English

全局数组保持为空

[英]Global array remains empty

I am trying to update my global array, but it remains null after I submit a text value(.name) through a submit button.我正在尝试更新我的全局数组,但在我通过提交按钮提交文本值(.name)后,它仍然是 null。

Please tell me how I can keep track of text values in my global array.请告诉我如何跟踪全局数组中的文本值。 Thank you.谢谢你。

var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
  document.querySelector("#form1").onsubmit = () => {
    let name = document.querySelector(".name").value;
    display_name.push(name);
};

});

When the form is submitted, a new page is loaded.提交表单时,会加载一个新页面。 It loads the URL in the action property of the form.它在表单的action属性中加载 URL。 So, your variable goes away.所以,你的变量消失了。

If you don't want that to happen, prevent the form from being submitted with preventDefault .如果您不希望这种情况发生,请阻止使用preventDefault提交表单。

For example...例如...

 const name_list = []; window.addEventListener('DOMContentLoaded', (e) => { const names = document.querySelector(`.names`); const add_button = document.querySelector(`.names--add_button`); names.addEventListener('submit', e => e.preventDefault()); add_button.addEventListener('click', (e) => { const name = document.querySelector(`.names--name`); const collected = document.querySelector(`.names--collected`); name_list.push(name.value); collected.innerHTML += `<li>${name.value}</li>`; name.value = ``; name.focus(); }); });
 body { background: snow; }
 <form class="names" action="#" method="post"> <label>Name: <input type="text" name="name" class="names--name"></label> <button class="names--add_button">Add To List</button> <div>Names Collected:</div> <ul class="names--collected"> </ul> </form>

I am see at the moment it's working perfect.我现在看到它工作得很好。 but you want add value every time when you click the button.但是您希望每次单击按钮时都增加价值。 so just changed the type of your <button type="submit"> to <button type="button">所以只需将您的<button type="submit">更改为<button type="button">

because when you click on submit page automatically reload in html, an the 2nd thing you need to change your event from onsubmit to onclick and your button to it instead of your form.因为当您单击提交页面时,html 中会自动重新加载,您需要将事件从onsubmit更改为onclick并将您的按钮改为它而不是您的表单。

var display_name = [];

document.addEventListener('DOMContentLoaded', () =>{
  document.querySelector("#button1").onclick = () => {
    let name = document.querySelector(".name").value;
    display_name.push(name);
  };
});

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

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