我正在做一个待办事项清单。我可以在一个字段中输入文本并使用复选框创建一个新项目,但我无法让复选框执行任何操作。我想在单击复选框后更改文本的颜色
function todoadd() {
todoNew = new objectTodo();
}
function objectTodo() {
var todo = document.getElementById('textinput').value;
var listItem = document.createElement("li");
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
listItem.appendChild(checkbox);
var itemText = document.createTextNode(todo);
listItem.appendChild(itemText);
document.getElementById('place').appendChild(listItem);
function changeColor(checkbox,itemText) {
var check = document.getElementById(checkbox);
var todoItem = document.getElementById(itemText);
if (check.checked == true) {
todoItem.style.backgroundColor="Red";
}
}
}

<title>ToDo</title>
<body>
<div id="container">
<div id="todoList">
<div id="textboxBackground">
<input type='text' id='textinput' placeholder='What do you need to do today?' />
<button type='button' id="myButton" class='button' onclick='todoadd()' value='Add to list' />Add To-do</button>
</div>
<ul id="place"></ul>
</div>
&#13;
答案 0 :(得分:0)
您需要将事件绑定到所有复选框。像下面这样的东西 -
var checkboxes = document.querySelector('checkbox');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].change(function() {
var text = this.parentNode.childNodes[]; // select the textnode here by giving the index to childNodes. Should be 0 or 1.
if (this.checked == true) {
text.style.backgroundColor="Red";
}
else {
text.style.backgroundColor="grey"; // set the original color here
}
});
}