复选框控制删除线功能异常:第二次迭代无法取消删除线求助
问题分析与修复方案
嘿,我一眼就看到你第二次代码里的问题啦——else分支里的目标元素搞错了!咱们来一步步拆解清楚:
错误根源
当你勾选复选框时,你正确地给对应的<p class="note">元素添加了删除线:
notePara[i].style.textDecorationLine = "line-through";
但取消勾选时,你却错误地操作了这个<p>元素的父容器(也就是.noteContainer):
notePara[i].parentElement.style.textDecorationLine = "none";
父容器本来就没被设置过删除线样式,这行代码等于做了无用功,自然看不到删除线被移除的效果。
修正后的核心代码
只需要把else分支的目标元素改回notePara[i]就行,和勾选时操作同一个元素:
let checkBoxes = document.getElementsByClassName("cbDone"); let notePara = document.getElementsByClassName("note"); const setLineThrough = () => { for (let i = 0; i < checkBoxes.length; i++) { if (checkBoxes[i].checked) { notePara[i].style.textDecorationLine = "line-through"; } else { // 修正:操作notePara[i]本身,而非父元素 notePara[i].style.textDecorationLine = "none"; } } };
更高效的优化建议
其实你没必要每次点击都遍历所有复选框,因为点击的就是当前触发事件的复选框,直接用this获取它,再找到对应的<p class="note">元素就好,逻辑更清晰也更高效:
HTML部分(仅修改onclick参数):
<div class="noteContainer"> <p class="title">Hello World</p> <p class="note">This is the hello world note!</p> <i class="fa fa-pencil-square-o noteEdit" title="Edit" aria-hidden="true"></i> <input onclick="setLineThrough(this)" type="checkbox" name="done" class="cbDone"> </div>
JavaScript部分:
const setLineThrough = (checkbox) => { // 通过复选框找到父容器,再定位到对应的note元素 const note = checkbox.closest('.noteContainer').querySelector('.note'); note.style.textDecorationLine = checkbox.checked ? "line-through" : "none"; };
这样不管你有多少个note容器,每个复选框只操作自己对应的那个note,完全避免了循环遍历的冗余。
内容的提问来源于stack exchange,提问作者M.Amin
相关产品推荐
相关产品推荐

