本质上,我将 notes[]
数组中的一些笔记渲染到我的页面,并为每个笔记添加一个按钮,单击该按钮时,将使用 splice()
,然后重新渲染剩下的音符。该按钮根据笔记的标题(由用户输入)赋予一个 id,它也被赋予一个类似的 id。
这只是个人项目的一些 Vanilla JS,今天早上环顾四周后,我还没有找到不处理 Vue、Angular 或其他一些框架/包的解决方案。
HTML
这是相关的 HTML:
<main>
<div id="container">
<form id="utilities">
<input type="text" name="userTitle" id="user-title" placeholder="Title" autocomplete="off">
<input type="text" name="userBody" id="user-body" placeholder="Body" autocomplete="off">
<div id="buttons">
<input type="submit" name="userSubmit" id="user-submit" value="Submit">
</div>
<input type="text" name="userFilter" id="user-filter" placeholder="Search" autocomplete="off">
</form>
<div id="results"></div>
</div>
</main>
JavaScript
以下 JS 片段都是按顺序排列的,只是为了便于阅读和评论而进行了拆分。
这是我要传递到和从中提取的数组。它需要标题、正文和 ID。
const notes = [{
title: 'Grocery List',
body: 'Buy milk, eggs, and bread',
id: 'grocery-list'
},
{
title: 'Workout Routine',
body: 'running, push-ups, rowing',
id: 'workout-routine'
}
]
这是我的函数,它从用户输入中获取标题和正文文本。它在 renderNotes()
中调用。
const results = document.querySelector('#results');
const createElement = function(noteTitle, noteBody) {
const newNote = document.createElement('div');
const newTitle = document.createElement('h3');
const newBody = document.createElement('p');
const newButton = document.createElement('div');
newTitle.textContent = noteTitle;
newTitle.classname = 'note-title';
newBody.textContent = noteBody;
newBody.className = 'note-body';
newButton.className = 'note-button';
newButton.innerHTML = '⮿';
newButton.id = `button-${newTitle.textContent.toLowerCase()}`.replace(' ', '-');
newNote.appendChild(newTitle);
newNote.appendChild(newButton);
newNote.appendChild(newBody);
newNote.className = "note";
newNote.id = newTitle.textContent.toLowerCase().replace(' ', '-');
results.appendChild(newNote);
}
renderNotes()
只是对该数组中的每个音符调用 createElement()
。然后我第一次调用它。
const renderNotes = function(list) {
console.log(list)
list.forEach(function(item) {
createElement(item.title, item.body)
})
}
renderNotes(notes);
这段代码似乎是我失败的地方。它应该获取每个按钮(在 createElement()
调用期间创建)并向其添加 eventListener('click')
。然后它应该查看 notes[]
中的每个笔记,找到与按下的按钮具有相似 id 的那个,然后 splice()
来自 notes[]
数组的注释。然后我只想重新渲染笔记。
document.querySelectorAll('.note-button').forEach(function(button) {
button.addEventListener('click', function(e) {
notes.forEach(function(note) {
if (e.target.id.includes(note.id)) {
notes.splice(notes.indexOf(note), 1)
}
renderNotes(notes)
})
})
});
实际结果
笔记似乎是从数组中一致拼接出来的,但我的问题在于让它们重新渲染。目前它只是删除项目,然后无法呈现或正在向页面添加更多副本。 编辑添加: 我在控制台中没有收到任何错误,代码只是在计算机方面正确执行。所以我知道这绝对是“椅子和键盘之间的问题”错误。
希望这是有道理的。感谢您的回复。
最佳答案
您在每次迭代时调用 renderNotes(notes)
,而不仅仅是在数组发生变化之后。
尝试这样的事情:
const clickedNote = notes.find(note => e.target.id.includes(note.id));
notes.splice(notes.indexOf(clickedNote), 1);
renderNotes(notes);
更好的解决方案是使用 let
定义 notes
,然后执行如下操作:
notes = notes.filter(note => !e.target.id.includes(note.id));
renderNotes(notes);
关于JavaScript - 在拼接数组中的项目然后将该数组重新呈现到我的页面时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56308180/