You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript实现对象筛选并将结果渲染至DOM

解决方案:筛选并渲染待办事项数组

我会先补全你的待办事项数组,然后一步步实现筛选和DOM渲染的功能:

1. 完善HTML结构

首先我们需要一个容器来展示筛选后的结果,给页面添加一个专属的列表容器:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ToDos</title>
</head>
<body>
    <h1>Todos....</h1>
    <!-- 添加用于展示筛选结果的容器 -->
    <div id="todo-container"></div>
    <script src='todo-app.js'></script>
</body>
</html>

2. 实现筛选与渲染的JavaScript代码

接下来补全todos数组,并编写筛选和渲染逻辑。这里我以筛选未完成的任务为例(你可以轻松修改条件来筛选已完成任务):

const todos = [
    { text: 'Order Cat food', completed: false },
    { text: 'Clean Kitchen', completed: true },
    { text: 'Buy Milk', completed: false },
    { text: 'Do Laundry', completed: true },
    { text: 'Walk the Dog', completed: false }
];

// 筛选函数:获取所有未完成的待办事项
function getIncompleteTodos(todos) {
    return todos.filter(todo => !todo.completed);
}

// 渲染函数:将筛选后的结果渲染到DOM中
function renderTodos(todos) {
    const todoContainer = document.getElementById('todo-container');
    // 先清空容器,避免重复渲染内容
    todoContainer.innerHTML = '';

    // 遍历筛选后的数组,为每个任务创建DOM元素
    todos.forEach(todo => {
        const todoItem = document.createElement('p');
        todoItem.textContent = todo.text;
        // 给已完成的任务添加删除线样式,方便视觉区分
        if (todo.completed) {
            todoItem.style.textDecoration = 'line-through';
            todoItem.style.color = '#888';
        }
        todoContainer.appendChild(todoItem);
    });
}

// 页面加载完成后,自动筛选并渲染未完成任务
const incompleteTodos = getIncompleteTodos(todos);
renderTodos(incompleteTodos);

代码说明

  • 筛选逻辑:利用数组的filter()方法,通过!todo.completed条件筛选出未完成任务。如果要筛选已完成任务,只需把条件改成todo.completed即可。
  • 渲染逻辑:先获取页面上的容器元素,清空原有内容后,遍历筛选后的数组为每个任务创建<p>元素,设置文本内容和样式,最后将元素添加到容器中。
  • 扩展功能:如果需要支持用户切换筛选条件,可以添加按钮并监听点击事件,比如:
<button id="show-incomplete">显示未完成</button>
<button id="show-completed">显示已完成</button>

对应的JS事件监听代码:

document.getElementById('show-incomplete').addEventListener('click', () => {
    renderTodos(getIncompleteTodos(todos));
});

document.getElementById('show-completed').addEventListener('click', () => {
    const completedTodos = todos.filter(todo => todo.completed);
    renderTodos(completedTodos);
});

内容的提问来源于stack exchange,提问作者MaleckH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:10:25