//Creates a remove button
var myListofTasks = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myListofTasks.length; i++) {
var span = document.createElement("SPAN");
span.innerHTML = "Remove ☒";
// var removeTxt = document.createTextNode("Remove ☒");
span.className = "byebye";
//span.appendChild(removeTxt);
myListofTasks [i].appendChild(span);
span.onclick = deleteItem;
}
function deleteItem(e) {
var li = e.target.parentElement;
var ul = document.getElementById("myTasks");
ul.removeChild(li);
}
// Creates a completed button
var creatingFinishBtn = document.getElementsByTagName("LI");
var x;
for (x = 0; x < creatingFinishBtn.length; x++) {
var button = document.createElement("BUTTON");
button.innerHTML = "Completed ★";
button.className = "complete";
creatingFinishBtn[x].appendChild(button);
button.onclick = highlightItem;
button.onclick.strikeThrough;
}
function strikeThrough(){
var list = document.querySelector('button');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('completed');
}
}, false);
}
function highlightItem(e) {
var li = e.target.parentElement;
var ul = document.getElementById("myTasks");
e.target.style.backgroundColor ="red";
}
我的css包含。带有删除线的文本装饰样式。
当单击完成的按钮时,我希望我的列表项删除。当我单击时,什么都没有发生,除了完成的按钮正在按预期更改颜色外。
答案 0 :(得分:1)
我稍微重构了您的代码。为了删除线,您可以使用内置CSS功能的text-decoration和line-through。
//Creates a remove button
const myListofTasks = document.getElementsByTagName("li");
const taskLen = myListofTasks.length;
var i = 0;
for (i = 0; i < taskLen; i++) {
// Append remove button
let deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "Remove ☒";
deleteBtn.className = "byebye";
deleteBtn.onclick = deleteItem;
myListofTasks[i].appendChild(deleteBtn);
// append complete button
let completeBtn = document.createElement("button");
completeBtn.innerHTML = "Completed ★";
completeBtn.className = "complete";
completeBtn.onclick = completeItem;
myListofTasks[i].appendChild(completeBtn);
}
function deleteItem(e) {
var li = e.target.parentElement;
var ul = document.getElementById("myTasks");
ul.removeChild(li);
}
function completeItem(e) {
var li = e.target.parentElement;
var ul = document.getElementById("myTasks");
e.target.style.backgroundColor = "red";
e.target.parentElement.style.setProperty("text-decoration", "line-through");
}
<ul id="myTasks">
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
<li>Item #5</li>
<li>Item #6</li>
<li>Item #7</li>
<li>Item #8</li>
<li>Item #9</li>
</ul>