【发布时间】:2021-09-09 14:44:17
【问题描述】:
输入数据即可,提交即可。但是,如果我刷新,输入的所有内容都会显示为对象对象。任何想法是为什么?
除此之外,每个输入都单独创建表数据,而不是在一个表中,每个输入将每个新创建的数据并排放置,而我希望它们像 justify-content: space-around 一样围绕空格。但它似乎没有这样做
对 JS 还是很陌生。我无法确切地找到我做错了什么。 JSON stringify 对我来说仍然是一种新的做法。所以,我不确定我所做的是否正确。
编辑 ------------ 谁能解释刷新后的格式发生了什么?
html
<h1>Library</h1>
<div id="login" class="login-btn">
<button class="User" id = "login">login</button>
</div>
<button id="clear">Clear</button>
<form id="form" action="">
<input class="input" type="text" id="input-title" placeholder="Title" required />
<input class="input" type="text" id="input-author" placeholder="Author" required/>
<input class="input" type="number" id="input-number" placeholder="Pages" required />
<input value="Submit" id="submitbtn" class="submit" type="submit">
</form>
<input type="checkbox" class="checkbox"><span> Check me if you read the book</span>
<table id="table">
</table>
<script src="script.js"></script>
</body>
</html>
js
//按钮
const buttonLogin = document.getElementById("login")
const table = document.getElementById("table")
const clearBtn = document.getElementById("clear")
const submitBtn = document.getElementById("submitbtn")
const form = document.getElementById("form")
const inputTitle = document.getElementById("input-title")
const inputAuthor = document.getElementById("input-author")
const inputNumber = document.getElementById("input-number")
//array local storage
let itemsArray = localStorage.getItem('items')
? JSON.parse(localStorage.getItem('items'))
: []
localStorage.setItem('items', JSON.stringify(itemsArray))
const data = JSON.parse(localStorage.getItem('items'))
const createBook = (text, text1, text2) => {
const tble = document.createElement('table')
const td = document.createElement('td')
const td2 = document.createElement('td')
const td3 = document.createElement('td')
td.textContent = text
td.style.color = ('black')
td.style.border = ('solid')
td.style.borderColor =('blueviolet')
td2.textContent = text1
td2.style.color = ('black')
td2.style.border = ('solid')
td2.style.borderColor = ('blueviolet')
td3.textContent = text2
td3.style.color = ('black')
td3.style.border = ('solid')
td3.style.borderColor =('blueviolet')
table.appendChild(td)
table.appendChild(td2)
table.appendChild(td3)
}
form.addEventListener('submit', function (e) {
e.preventDefault()
//for (var i = 0; i < 2; i++) {
itemsArray.push(inputTitle, inputAuthor, inputNumber)
localStorage.setItem('items', JSON.stringify(itemsArray))
createBook(inputTitle.value, inputAuthor.value, inputNumber.value)
inputTitle.value = ''
inputAuthor.value= ''
inputNumber.value= ''
// }
})
data.forEach ((item) => {
createBook(item)
})
//clear list
clearBtn.addEventListener('click', function () {
localStorage.clear()
while (table.firstChild) {
table.removeChild(table.firstChild)
}
})
【问题讨论】:
-
你能把它简化为一个最小的例子吗?我确信我们不需要所有这些代码来重现问题……
-
对不起,是的。刚刚做到了。
-
为什么需要
data和itemsArray?他们不一样吗?
标签: javascript html json