很抱歉提出这个非常具体的问题。我想为我和我的女朋友制作一个简单的购物车应用程序。为了存储数据,我想使用一个.。我第一次试过了,效果很好。但现在我被困住了。
我的UI.showData()应该将条目数组的所有数据打印到我的页面上。当我使用for(let i=0;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>
发布于 2022-09-26 17:14:51
您正在传递事件侦听器返回值,而不是监听器本身。它应该是:
window.addEventListener('DOMContentLoaded', (e) => UI.showData(items));而且,在脚本运行时,项只是一个空数组,因此不会呈现任何内容。
https://stackoverflow.com/questions/73857579
复制相似问题