[英]How to add/remove class from a parent List-item(li) when their child checkbox is changed in javascript?
我正在用Javascript構建一個簡單的Todo應用程序,但是在嘗試將類添加到作為復選框父級的List-item(li)時遇到了麻煩。
默認情況下,未選中列表項(Todo)復選框(未添加任何類)。 每當用戶選中待辦事項復選框時,都會添加一個類,並且待辦事項文本會通過一行。
我設法使其正常工作,但沒有任何反應。
// ADD ITEM, REMOVE ITEM - FUNCIONALITY const btn = document.getElementById('btn'); const ulList = document.getElementById('list'); // Button event listener with adding li elemnts with input value btn.addEventListener('click', function() { var input = document.getElementById('input').value; // Capture input value var newItem = document.createElement("LI"); // Create a <li> node newItem.innerHTML = input + '<input type="checkbox" class="checkboxes" ><p class="delet">x</p>'; // Add content to li element for todo. ulList.insertBefore(newItem, ulList.childNodes[0]); // Insert <li> before the first child of <ul> // input = ' '; // Reset input value to empty field // Remove item funcionality newItem.childNodes[2].onclick = function() { this.parentNode.remove(this); } }) // ********** IMPORTANT CODE BELOW *********************** // MARK DONE TODO - FUNCIONALITY var checkBox = document.getElementsByClassName('checkboxes'); for (var i = 0; i < checkBox; i++) { checkBox[i].addEventListener('change', function() { if (this.checked) { // Checkbox is checked.. this.parentNode.classList.add("line-through"); } else { // Checkbox is not checked.. this.parentNode.classList.remove("line-through"); } }); }
.line-through { text-decoration: line-through; }
<p class="lead text-center">Welcome to my todoList applications</p> <div class="row"> <form id="form" class="col-lg-6 col-8 mx-auto"> <div class="input-group"> <input type="text" id="input" class="form-control"><span> <button id="btn" type="button" class="btn btn-primary">Submit</button></span> </div> </form> </div> <div class="row"> <ul id="list" class="list col-lg-6 col-8 mx-auto"> <!-- <li>this is a todo item <input type="checkbox" class="checkbox"></li> <li>this is a todo item <input type="checkbox" class="checkbox"></li> --> </ul> </div> <div class="row"> <button id="btnClr" type="button" class="btn btn-primary mx-auto btnHide">Clear All Todos</button> </div>
我將不勝感激任何幫助。 預先感謝大家! :)
下面是一個完整且有效的示例。 一般來說,對我這樣的任務來說,使用document.createElement
而不是.innerHTML
更容易(對我來說,您的個人經歷可能會有所不同),因為(再次,將事件偵聽器附加到由document.createElement
創建的元素上)容易得多。
只要單擊“提交”按鈕,該示例就會創建一個新的<li>
, <input type="checkbox">
, <span>
(用於待辦事項的標題)和一個<button>
(用於刪除待辦事項)。 創建所有內部元素之后,可以輕松地使用.appendChild
將它們添加到<li>
。
我嘗試使用描述性名稱,因此遵循起來應該並不復雜。
const todoAddBtn = document.getElementById('btn'); const todoDeleteBtn = document.getElementById('btnClr'); const todosList = document.getElementById('list'); const todoInput = document.getElementById('input'); todoAddBtn.addEventListener('click', function(){ const todoTopic = readAndClearValue(todoInput); const todoLi = createListItem(); const todoCheckbox = createCheckbox(); const todoTitle = createTitle(todoTopic); const todoDelete = createDeleteButton(); todoLi.appendChild(todoCheckbox); todoLi.appendChild(todoTitle); todoLi.appendChild(todoDelete); todosList.insertBefore(todoLi, todosList.firstElementChild); }); todoDeleteBtn.addEventListener('click', function () { todosList.innerHTML = ''; }); // readAndClearValue :: HTMLElement -> String function readAndClearValue (element) { const value = element.value; element.value = ''; return value; } // createListItem :: () -> HTMLElement function createListItem () { return document.createElement('li'); } // createTitle :: String -> HTMLElement function createTitle (text) { const title = document.createElement('span'); title.textContent = text; return title; } // createDeleteButton :: () -> HTMLElement function createDeleteButton () { const button = document.createElement('button'); button.textContent = 'X'; button.className = 'delet'; button.addEventListener('click', function () { button.parentNode.removeChild(button); // to remove the <li>, use something like // button.parentNode.parentNode.removeChild(button.parentNode) // or button.closest('li').remove() if supported }); return button; } // createCheckbox :: () -> HTMLElement function createCheckbox () { const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.className = 'checkboxes'; checkbox.addEventListener('change', function () { if (checkbox.checked) { checkbox.parentNode.classList.add('line-through'); } else { checkbox.parentNode.classList.remove('line-through'); } }); return checkbox; }
.line-through { text-decoration: line-through; }
<p class="lead text-center">Welcome to my todoList applications</p> <div class="row"> <form id="form" class="col-lg-6 col-8 mx-auto"> <div class="input-group"> <input type="text" id="input" class="form-control" > <button id="btn" type="button" class="btn btn-primary">Submit</button> </div> </form> </div> <div class="row"> <ul id="list" class="list col-lg-6 col-8 mx-auto"> </ul> </div> <div class="row"> <button id="btnClr" type="button" class="btn btn-primary mx-auto btnHide"> Clear All Todos </button> </div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.line-through li {
text-decoration: line-through;
}
</style>
</head>
<body>
<p class="lead text-center">Welcome to my todoList applications</p>
<div class="row">
<form id="form" class="col-lg-6 col-8 mx-auto">
<div class="input-group">
<input type="text" id="input" class="form-control" ><span>
<button id="btn" type="button" class="btn btn-primary">Submit</button></span>
</div>
</form>
</div>
<div class="row">
<ul id="list" class="list col-lg-6 col-8 mx-auto">
<!-- <li>this is a todo item <input type="checkbox" class="checkbox"></li>
<li>this is a todo item <input type="checkbox" class="checkbox"></li> -->
</ul>
</div>
<div class="row">
<button id="btnClr" type="button" class="btn btn-primary mx-auto btnHide">Clear All Todos</button>
</div>
</body>
<script>
// ADD ITEM, REMOVE ITEM - FUNCIONALITY
const btn = document.getElementById('btn');
const ulList = document.getElementById('list');
let checkBox = document.querySelectorAll('.checkboxes li');
// Button event listener with adding li elemnts with input value
btn.addEventListener('click', function(){
var input = document.getElementById('input').value; // Capture input value
var newItem = document.createElement("LI"); // Create a <li> node
newItem.innerHTML = input + '<input type="checkbox" class="checkboxes" ><p class="delet">x</p>'; // Add content to li element for todo.
ulList.insertBefore(newItem, ulList.childNodes[0]); // Insert <li> before the first child of <ul>
// input = ' '; // Reset input value to empty field
// Remove item funcionality
newItem.childNodes[2].onclick = function() {this.parentNode.remove(this);}
});
// ********** IMPORTANTO CODE BELOW ***********************
// MARK DONE TODO - FUNCIONALITY
document.body.addEventListener( 'click', function ( event ) {
if (event.srcElement.className == 'checkboxes') {
console.log(this);
this.classList.toggle('line-through');
}
});
checkBox.forEach(el => {
el.addEventListener('change', myFunction);
}, false);
function myFunction(){
if(this.checked) {
console.log('here')
this.classList.toggle('line-through');
}
}
</script>
</html>
似乎您需要在創建復選框后添加偵聽器。 現在發生了問題加載頁面,並且在開始時沒有任何復選框,因此在運行for循環時不附加任何處理程序
這里是如何使其工作的片段。 有很多更改,但我嘗試留下詳細的評論。
隨時詢問您是否有任何問題:)
https://codesandbox.io/embed/bootstrap-r3ud0
這也是JS部分。
const btn = document.getElementById("btn"); const ulList = document.getElementById("list"); // Button event listener with adding li elemnts with input value btn.addEventListener("click", function() { var input = document.getElementById("input").value; // Capture input value var newItem = document.createElement("LI"); // Create a <li> node // manually create input element var inputEl = document.createElement("input"); // set attributes inputEl.type = "checkbox"; inputEl.class = "checkboxes"; // also create p element var xmark = document.createElement("p"); xmark.innerHTML = "x"; xmark.class = "delet"; // set click handler xmark.onclick = function() { this.parentNode.remove(this); }; // most important part! // we add change listener on input create step inputEl.addEventListener("change", changeHandler); newItem.innerHTML = input; // and append our new elements to the li newItem.appendChild(inputEl); newItem.appendChild(xmark); ulList.insertBefore(newItem, ulList.childNodes[0]); // Insert <li> before the first child of <ul> }); // create separate handler for change event (first param is event) const changeHandler = event => { // we can access checked property of an element const checked = event.target.checked; // also we need the target (input in this case) for further manipulations const element = event.target; if (checked) { // Checkbox is checked.. element.parentNode.classList.add("line-through"); } else { // Checkbox is not checked.. element.parentNode.classList.remove("line-through"); } };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.