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

将简易待办事项清单的jQuery代码转为纯JS或React组件

嘿,我帮你把这个jQuery的待办清单转换成纯JavaScript和React组件两种版本啦,下面是详细的实现代码和说明:

纯JavaScript版本

先保留原有的HTML结构(不用做修改):

<div class="todo-list container">
  <ul class="list-your-todo">
    <li>
      <input type="text" name="name" class="form-control" placeholder="Name" value="" />
      <p class="deleteList">- Delete this</p>
    </li>
  </ul>
  <p class="addList">+ Add another</p>
</div>

接下来是替代jQuery功能的纯JS代码:

// 等待DOM完全加载后执行逻辑
document.addEventListener('DOMContentLoaded', function() {
  const addBtn = document.querySelector('.addList');
  const todoUl = document.querySelector('.list-your-todo');
  const firstLi = todoUl.querySelector('li');

  // 点击"添加"按钮的逻辑
  addBtn.addEventListener('click', function() {
    // 深克隆第一个li元素(包含所有子元素)
    const newLi = firstLi.cloneNode(true);
    // 清空克隆出来的输入框,避免继承原输入框的内容
    newLi.querySelector('input').value = '';
    // 添加上原逻辑里的样式类
    newLi.classList.add('clearfix', 'showIcon');
    todoUl.appendChild(newLi);
  });

  // 删除项的逻辑(用事件委托处理动态生成的元素)
  todoUl.addEventListener('click', function(e) {
    if (e.target.classList.contains('deleteList')) {
      e.target.parentElement.remove();
    }
  });
});

这里用DOMContentLoaded替代了jQuery的初始化函数,用原生的querySelector获取元素,通过事件委托给父元素绑定点击事件,这样动态添加的删除按钮也能正常触发删除逻辑。

React函数组件版本

这个版本采用React的状态管理思维,更符合React的开发模式:

import { useState } from 'react';

function TodoList() {
  // 用数组维护待办项列表,初始默认有一个空项
  const [todos, setTodos] = useState([{}]);

  // 添加新待办项的方法
  const handleAddTodo = () => {
    setTodos([...todos, {}]);
  };

  // 删除指定索引的待办项
  const handleDeleteTodo = (index) => {
    const updatedTodos = todos.filter((_, idx) => idx !== index);
    setTodos(updatedTodos);
  };

  return (
    <div className="todo-list container">
      <ul className="list-your-todo">
        {todos.map((_, index) => (
          <li 
            key={index} 
            className={index !== 0 ? 'clearfix showIcon' : ''}
          >
            <input
              type="text"
              name="name"
              className="form-control"
              placeholder="Name"
              value=""
            />
            <p 
              className="deleteList" 
              onClick={() => handleDeleteTodo(index)}
            >
              - Delete this
            </p>
          </li>
        ))}
      </ul>
      <p className="addList" onClick={handleAddTodo}>
        + Add another
      </p>
    </div>
  );
}

export default TodoList;

这里用useState钩子管理待办项数组,点击添加按钮时通过扩展运算符更新数组;删除时通过filter方法移除对应索引的项。每个列表项用索引作为key(如果后续需要给待办项添加自定义内容,建议改用唯一ID),并且只有非第一个项会添加上clearfix showIcon类,和原jQuery逻辑保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:50:28