jquery - 有没有办法将 Jquery 所做的 HTML 元素类更改保存在生成​​的 EJS 文件中?

标签 jquery node.js mongoose ejs

我有一个待办事项列表 Node 项目,其中每个待办事项列表都保存为 MongoDB 中的一个实体,如下所示:

var todoSchema = new mongoose.Schema({
  items: [String]
});

当用户单击待办事项列表中的一项时,它会通过更改所单击元素的 CSS 类将其划掉。当用户刷新时,该类将更改回 EJS 文件呈现它的方式。

我希望划掉的是本地的,即只有划掉某个项目的人才会看到它被划掉。有没有什么方法可以做到这一点,而不涉及为每个用户提供单独的数据库条目?

前条目:

{
    "_id": {
        "$oid": "59bf2fed71c3840508539b29"
    },
    "item": [
        "ayy",
        "yyaa",
        "yyaaaafyyy"
    ],
    "__v": 0
}

最佳答案

好的,这是一个实用的解决方案:

后端

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> 上方的 JavaScript

<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>

关于jquery - 有没有办法将 Jquery 所做的 HTML 元素类更改保存在生成​​的 EJS 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46374555/

相关文章:

javascript - 将 .each() 绑定(bind)到动态添加的元素

node.js - 为什么我的 swig 模板无法在 MEAN Web 应用程序中呈现?

javascript - 更新给定索引的数组值(mongoose,mongodb)

Node.js:如何将 Mongoose 结果传递给我的 socket.emit

jQuery 按数据属性中的日期排序

javascript - 从数组中选择元素时出现意外标识符

node.js - npm 从本地文件夹安装包

javascript - 何时在 Mongoose 中使用 new ObjectId ("string-id")而不是 ObjectId ("string-id")?

jQuery - 从外部脚本 Hook $.ajax 调用

javascript - 使用 Nightmare JS 延迟加载滚动