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

原生JavaScript Todo列表勾选复选框如何仅给对应待办项添加样式

问题根因说明

  1. 你对closest()方法的使用错误:closest()只会向上遍历DOM树查找祖先元素,无法查找同级相邻元素,所以你拿不到对应的待办输入框。
  2. 变量赋值逻辑错误:原代码中let toDo = tgt.closest("input").classList.contains("input")是将布尔值赋值给toDo变量,布尔值不存在value和style属性,自然不会产生样式变化。
  3. 旧代码全量修改样式的问题:你没有关联当前触发事件的复选框和对应待办项,直接遍历全部待办项修改,自然会给所有项加样式。
  4. allCheckboxes为空的问题:querySelectorAll返回的是静态NodeList,只会保存调用方法时页面已存在的元素。你在页面初始化时就获取了复选框列表,此时还没有新增待办项,所以列表为空,后续新增的复选框也不会自动加入该列表。

修正后实现代码

你用事件委托的思路是对的,不用单独给每个复选框绑定事件,动态新增的元素也能触发:

toDoContainer.addEventListener("change", function(e) {
    const tgt = e.target;
    // 仅处理复选框的change事件
    if (!tgt.classList.contains("checkbox")) return
    // 查找相邻的待办输入框,若输入框在复选框前面就换成previousElementSibling
    const toDoInput = tgt.nextElementSibling
    // 校验待办输入框有效性
    if (!toDoInput || !toDoInput.classList.contains("input") || toDoInput.value.trim() === "") return
    // 根据勾选状态切换样式
    if (tgt.checked) {
        toDoInput.style.textDecoration = "line-through"
        toDoInput.style.opacity = "50%"
    } else {
        toDoInput.style.textDecoration = "none"
        toDoInput.style.opacity = "100%"
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:21:01