首页 > 解决方案 > 无法将复选框属性应用于 for 循环

问题描述

好吧,所以我希望我只是错过了一些简单的事情。基本上我正在制作一个待办事项列表,我希望每个列表项都出现一个复选框(这有效)。当用户单击复选框时, textDecoration = "line-through" 应该通过 listItem 类。这意味着一条线贯穿了该人创建的待办事项。这是我主要使用的代码:

function show() {
var todos = get_todos();

var html = '<ul>';
for(var i=0; i < todos.length; i++) {
    html += '<span><li class="listItem" style="float:left;">' + todos[i] + '</li><input class="checkBox" type="checkbox">' + '<button class="remove" id="' + i  + '"><i class="fa fa-trash" aria-hidden="true"></i></button></span><br/>';
};
html += '</ul>';

document.getElementById('todos').innerHTML = html;

var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', remove);
};

////////////////////////////////////
//Everything above here works. Below is the checkbox issue

var checkBox = document.getElementsByClassName("checkBox");
var listItem = document.getElementsByClassName("listItem");

for (var i=0; i < checkBox.length; i++) {
    if (checkBox.checked == true){
        listItem.style.textDecoration = "line-through";
    }else {
        listItem.style.textDecoration = "none";
    }
};}

我现在所处的位置是,如果我在原始复选框中创建一个 onClick 函数,我可以使用该 if/else 语句并且它有点工作。如果我使用 document.getElementsByClassName 设置 checkBox/listItems 变量,它将不起作用,但如果我使用 document.getElementById,它将起作用。问题是它只适用于用户创建的第一个任务,而没有其他任务之后创建。我假设这是因为 Id 仅适用于一个元素(与适用于多个元素的类不同),或者因为它不像上面的代码那样循环通过 for 循环。

TL/DR基本上,当我运行上面的代码时,我不断收到“Uncaught TypeError: Cannot set property 'textDecoration' of undefined at show (todo.js:57) at todo.js:75”。

当我为复选框创建一个单独的函数并使用 elementbyid 而不是 elementsbyclass 时,我没有收到此错误(也更改了上面 html 部分的 id/class)

我真的很想让这些直通效果适用于所有任务,而不仅仅是第一个任务。任何想法都非常感谢。感谢大家!

标签: javascriptfor-loopif-statement

解决方案


我会用css而不是javascript来完成这个(如果可能的话,这通常是我的规则)。在这种情况下,你必须对你的标记做一个小改动:因为没有previous-sibling选择器,你必须把s 放在input相应的 s 之前li,但是因为lisfloat:left仍然呈现完全相同。

input:checked + li {
  text-decoration:line-through;
}
<ul>
<span><input class="checkBox" type="checkbox"><li class="listItem" style="float:left;">foo</li><button class="remove" id="' + i  + '"><i class="fa fa-trash" aria-hidden="true"></i></button></span><br/>
<span><input class="checkBox" type="checkbox"><li class="listItem" style="float:left;">bar</li><button class="remove" id="' + i  + '"><i class="fa fa-trash" aria-hidden="true"></i></button></span><br/>
<span><input class="checkBox" type="checkbox"><li class="listItem" style="float:left;">baz</li><button class="remove" id="' + i  + '"><i class="fa fa-trash" aria-hidden="true"></i></button></span><br/>
</ul>


推荐阅读