本质上,我正在将notes[]
数组中的几个注释渲染到我的页面上,并在每个注释中添加一个按钮,当单击时,将使用splice()
删除数组的注释,然后重新渲染其余的笔记。该按钮根据注释标题(用户为输入给出(给出ID,该标题也给出了类似的ID。
这只是一个个人项目的一些香草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的一个,以及notes[]
阵列中的splice()
。然后,我只想重新渲染笔记。
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);