簡體   English   中英

為什么加載頁面時“showData()”不打印我的 arrays 值?

[英]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.

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