我有一个待办事项列表节点项目,其中每个待办事项列表都保存为MongoDB中的实体,如下所示:
var todoSchema = new mongoose.Schema({
items: [String]
});
当用户单击待办事项列表中的一个项目时,它会通过更改单击的元素的CSS类来将其交叉。当用户刷新时,该类将更改回EJS文件的呈现方式。
我希望十字架是本地的,即只有划掉一件物品的人才会看到它被划掉。有没有办法做到这一点,并不涉及为每个用户分别设置DB条目?
ex entry:
{
"_id": {
"$oid": "59bf2fed71c3840508539b29"
},
"item": [
"ayy",
"yyaa",
"yyaaaafyyy"
],
"__v": 0
}
答案 0 :(得分:1)
好的,这是一个功能性解决方案:
后端
app.get('/testing', (req, res, next) => {
const todoItems = {
'_id': {
'$oid': '59bf2fed71c3840508539b29'
},
'items': [
{ id: 0, todo: 'ayy' },
{ id: 1, todo: 'yyaa' },
{ id: 2, todo: 'yyaaaafyyy' }
],
'__v': 0
}
res.render('testing', {
todoItems
})
})
前端
<style>
.complete {
text-decoration: line-through;
}
</style>
将您的商品放入列表中。事件监听器将添加到元素内的每个<li>
元素,ID为:#todo
<ul id="todo">
<% todoItems.items.forEach((item) => { %>
<li id="<%- item.id %>">
<%= item.todo %>
</li>
<% }) %>
</ul>
这是一些放在</body>
<script>
// Define a function that takes input of an HTML element
// and then toggles the CSS class
// then checks localStorage to see if the item is in it
// if not, add it
// if so, remove it
const toggleComplete = (item) => {
item.classList.toggle('complete')
const isComplete = localStorage.getItem(item.innerText)
if (!isComplete) {
localStorage.setItem(item.innerText, 'complete')
return
}
localStorage.removeItem(item.innerText)
}
// When the page loads, add an event listener to each <li>
const items = document.querySelectorAll('#todo li')
items.forEach((item) => item.addEventListener('click', () => toggleComplete(item)))
// If the user leaves and comes back, we reinitialize
// We step through the same array we add event listeners to
// if the todo item is in localStorage, add the CSS class
const reinitializeSession = () => {
items.forEach((item) => {
const isComplete = localStorage.getItem(item.innerText)
if (!isComplete) return
item.classList.add('complete')
})
}
reinitializeSession()
</script>