【发布时间】:2019-02-15 18:05:13
【问题描述】:
好吧,我希望我只是错过了一些简单的事情。基本上我正在制作一个待办事项列表,我希望每个列表项都出现一个复选框(这有效)。当用户单击复选框时, 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 在展会上 (todo.js:57) 在 todo.js:75"。
当我为复选框创建一个单独的函数并使用 elementbyid 而不是 elementsbyclass 时,我没有收到此错误(也更改了上面 html 部分的 id/class)
我真的想让这些直通效果适用于所有任务,而不仅仅是第一个任务。任何想法都非常感谢。谢谢大家!
【问题讨论】:
-
您必须使用 checkBox[i] 并找到合适的 listItem[i] 来设置 textDecoration,目前您正在检查整个列表(checkBox)
-
listItem是元素集合,style不是元素集合的属性,所以style是undefined,所以不能在上面设置textDecoration。您必须遍历每个listItem元素才能以这种方式设置属性。 (同样适用于checkBox(它是一个集合)) -
因此,当我尝试按照
var checkBoxes = document.getElementsByClassName("checkBox"); var listItems = document.getElementsByClassName("listItem"); for (var i=0; i < checkBoxes.length; i++) { if (checkBoxes[i].checked == true){ listItems[i].style.textDecoration = "line-through"; }else { listItems[i].style.textDecoration = "none"; } };}的方式进行操作时,我没有收到任何控制台错误,但单击该复选框时不会执行任何操作。有什么想法吗?
标签: javascript for-loop if-statement