You are re-creating the whole table every time a todo is added or removed. And to create that table, you use the todos
Array, which does not store the status of a todo. You need to store it when it changes. The usual way to do that is to add a Boolean to it (true
or false
), so they look like:
{ task: 'Buy chocolate', done: false }
You can then use that status in the showTodosOnDiv
to determine whether you add a done
class to a <tr>
:
var trClass = todos[i].done ? 'done' : ''; // Use the status to add a class or not
/* The line above is equivalent to:
var trClass = '';
if (todos[i].done) { trClass = 'done'; }
*/
htmlcode += "<tr class='" + trClass + "'><td>" /* ... */
And add styles for that class in your CSS:
tr.done { background: lime; }
For example:
var taskInput = document.getElementById("taskInput"),
display = document.getElementById("display"),
todos = [];
function changeStatus(index) {
todos[index].done = !todos[index].done; // Revert the status
showTodosOnDiv();
}
function deleteTodo(index) {
todos.splice(index, 1);
showTodosOnDiv();
}
function showTodosOnDiv() {
var htmlcode = "<table>";
for (var i = 0; i < todos.length; i++) {
var trClass = todos[i].done ? 'done' : ''; // Use the status to add a class or not
htmlcode += "<tr class='" + trClass + "'><td>" + todos[i].task + "</td><td><button onclick='deleteTodo(" + i + ")'>✖</button><button onclick='changeStatus(" + i + ")'>✓</button></td></tr>";
}
htmlcode += "</table>";
display.innerHTML = htmlcode;
}
function add() {
var todo = { task: taskInput.value, done: false }; // Make it false by default
taskInput.value = "";
todos.push(todo);
showTodosOnDiv();
}
table { border: 1px solid; padding: 13px; }
td { border: 1px solid; padding: 13px; }
/* Add styles to this class */
tr.done { background: lime; }
<div id="display"></div>
Task <input type="text" id="taskInput" /><br/>
<button onclick="add();">Add</button>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…