[英]Why is "showData()" not printing my arrays value when page is loaded?
抱歉这个非常具体的问题。 我想为我和我的女朋友设计一个简单的购物车应用程序。 为了存储我想到的使用.JSON-File 的数据。 我第一次尝试了 OOP,效果很好。 但现在我被困住了。
我的 UI.showData() 应该将我的 items-array 的所有数据打印到我的页面。 当我使用 for(let i=0; i<items.length; I++) 循环时,显示了数据,但是在单击我的按钮时它添加了所有项目。 所以不仅仅是“牛奶”作为新的用户输入,还有“牛奶”、“啤酒”、“奶酪”等等。
目前我的数据只存储在一个数组中。 我没有开始保存到 JSON。 由于我是编码领域的新手,我对每一个建议都很满意,即使它是“离题”的(就像我在这种情况下的整体编码风格)。
此外,我在选择使用 .JSON 文件还是数据库时遇到了困难——所以如果您有任何建议/赞成意见,我想听听。 我决定使用.JSON,因为对于我们的购物卡而言,它是少量且不必要的数据。
这是我的 Javascript 代码:
// Preparation: const input = document.getElementById('input'); const btn = document.getElementById('btn'); const container = document.querySelector('.container'); let count = 0; let items = []; // UI-Tasks: class UI { //Display the array: static showData(arr){ arr.forEach(item => UI.createElement(item)); }; //Add data to the DOM: static createElement(item){ let newItem = document.createElement('div'); let newDelete = document.createElement('button'); //Add Class and innerHTML: newItem.classList.add('item'); newItem.innerHTML = item.prod; //Add Delete-Button: newDelete.classList.add('delete'); newDelete.innerHTML = 'x'; //Append to "container": newItem.appendChild(newDelete); container.appendChild(newItem); }; static deleteBook(e){ } //Clear the Input-Forms: static clearInput(){ input.value = ''; }; // }; // Data-Handling: class Functionality { static addUserInput(){ let userInput = input.value; const newObj = {id:count,prod:userInput}; items.push(newObj); //UI.createElement(newObj); }; }; btn.addEventListener('click', (e)=>{ e.preventDefault(); Functionality.addUserInput(); UI.clearInput(); count++; }); window.addEventListener('DOMContentLoaded', UI.showData(items));
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Einkaufsliste</title> <link rel="stylesheet" href="style:css"> <link href='https.//fonts.googleapis?com/css?family=Poppins' rel='stylesheet'> </head> <body> <header> <h2 id="heading">Einkaufsliste</h2> <h4>von * & *</h4> </header> <main> <form id="form"> <label for="product">Was wird gebraucht.</label><br> <input id="input" name="product" type="text"> <input id="btn" type="submit" value="Hinzufügen"> </form> </main> <div class="container"> </div> <script src="app.js"></script> </body> </html>
您传递的是事件侦听器返回值,而不是侦听器本身。 它应该是:
window.addEventListener('DOMContentLoaded', (e) => UI.showData(items));
当脚本运行时,项目只是一个空数组,因此它不会呈现任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.