【发布时间】:2021-01-06 01:36:40
【问题描述】:
我在尝试通过单击按钮将输入保存到本地存储时遇到问题。
我希望按钮查看它自己的 div,找到与之关联的输入并仅使用原生 JavaScript 保存到本地存储。
不一定要寻找交给我的答案,但也许可以通过步行或我可以看看的资源/项目会有所帮助。我还是个初学者,所以不能 100% 确定所有内容的名称或查找内容。
let times =
[
{time:'5:00 a.m.', key: 1},
{time:'6:00 a.m.', key: 2},
{time:'7:00 a.m.', key: 3},
{time:'8:00 a.m.', key: 4},
{time:'9:00 a.m.', key: 5},
{time:'10:00 a.m.', key: 6},
{time:'11:00 a.m.', key: 7},
{time:'12:00 p.m.', key: 8},
{time:'1:00 p.m.', key: 9},
{time:'2:00 p.m.', key: 10},
{time:'3:00 p.m.', key: 11},
{time:'4:00 p.m.', key: 12},
{time:'5:00 p.m.', key: 13},
{time:'6:00 p.m.', key: 14},
{time:'7:00 p.m.', key: 15},
{time:'8:00 p.m.', key: 16},
{time:'9:00 p.m.', key: 17},
{time:'10:00 p.m.', key: 18}
];
// mock localStorage to make this code runnable in StackOverflow
mockLocalStorage = {
getItem: function(key) {
const found = times.find(el => el.key === key);
}
}
function genList() {
for (let i = 0; i < times.length; i++) {
let newTimeBlock = document.createElement('form')
newTimeBlock.classList.add('row', 'hour');
newTimeBlock.setAttribute('key', times[i].key);
document.querySelector('.dailyList').appendChild(newTimeBlock);
//add the individual col per row
//time Column
let timeText = document.createElement('p');
timeText.classList.add('col-2')
timeText.textContent = times[i].time;
newTimeBlock.appendChild(timeText);
//input column
let inputText = document.createElement('input');
inputText.classList.add('col-9')
inputText.style.width = '100%';
inputText.id = 'inputs';
// mock localStorage to make this code snippet runnable
inputText.value = mockLocalStorage.getItem(times[i].key)
newTimeBlock.appendChild(inputText);
//save button column
let saveBut = document.createElement('button')
saveBut.classList.add('col-1', 'save');
saveBut.textContent = 'Save';
newTimeBlock.appendChild(saveBut);
}
}
genList();
<div class="dailyList"></div>
【问题讨论】: