#javascript #html #css
#javascript #HTML #css
Вопрос:
Как мне выделить серым цветом элемент списка, когда установлен флажок?
Текущий код, который у меня есть, преобразует текст, введенный в текстовое поле, в функцию, вызываемую createNote
при нажатии кнопки добавления. В функции текст добавляется к элементу списка, который затем добавляется в неупорядоченный список. Элемент списка имеет флажок внутри него. Я хочу, чтобы элемент списка стал серым и имел вычеркивание, когда его флажок установлен. Я не могу использовать jquery или другие библиотеки javascript для этого. Это то, что у меня есть в настоящее время:
<head>
<meta charset ="UTF-8">
<meta name="description" content="Website">
<title>Note Manager</title>
<script>
function createNote (form) {
//Gets the text for the note from the input box
var noteText = form.inputbox.value;
//Creates the note and adds the text to it
var note = document.createElement("li");
note.innerHTML = noteText
//Creates checkbox
var noteCheck = document.createElement("input")
noteCheck.type = "checkbox"
noteCheck.classList.add("checkcheck")
//Appends checkbox to the note
note.appendChild(noteCheck)
//Gets the unordered list and appends the note to it
document.getElementById("abc").appendChild(note)
}
function grayCheckedItems(){
//Gets the unordered list
var list = document.getElementById("abc");
//Gets list items from unordered list
var listItems = list.getElementsByTagName("li");
//Incorrect part. Needs to cycle through the list items and gray out the items that have checked checkboxes
for(var i = 0; i < listItems.length; i ){
var chekbox = listItems[i].getElementsByTagName("input")
if(chekbox.checked == true){
listItems[i].classList.add("completedItem")
}
}
}
</script>
<style>
.completedItem{
color: gray;
text-decoration: line-through;
}
</style>
</head>
<body>
<form name="myform">
Enter a note: <br/>
<input type="text" name="inputbox">
<input type="button" name="button" Value="Add" onClick="createNote(this.form)">
</form>
<main>
<h2>Task List: </h2>
<ul id="abc" onchange="grayCheckedItems(this.ul)">
</ul>
</main>
</body>
Как мне это сделать? Текущий код не выделяет серым цветом элементы списка, которые отмечены. Я пытался искать похожие проблемы в Интернете, но все они были разными, потому что флажок был создан путем ввода его в html. В этой задаче все флажки создаются с использованием javascript.
Ответ №1:
Я добавил onclick
обработчик в вашу процедуру создания флажка, который добавляет или удаляет ваш .completeItem
класс. Посмотрите ниже.
function createNote(form) {
//Gets the text for the note from the input box
var noteText = form.inputbox.value;
//Creates the note and adds the text to it
var note = document.createElement("li");
note.innerHTML = noteText
//Creates checkbox
var noteCheck = document.createElement("input")
noteCheck.type = "checkbox"
noteCheck.classList.add("checkcheck")
noteCheck.onclick = function() {
if (this.checked == true) {
this.parentNode.classList.add("completedItem");
} else {
this.parentNode.classList.remove("completedItem");
}
}
//Appends checkbox to the note
note.appendChild(noteCheck)
//Gets the unordered list and appends the note to it
document.getElementById("abc").appendChild(note)
}
function grayCheckedItems() {
//Gets the unordered list
var list = document.getElementById("abc");
//Gets list items from unordered list
var listItems = list.getElementsByTagName("li");
//Incorrect part. Needs to cycle through the list items and gray out the items that have checked checkboxes
for (var i = 0; i < listItems.length; i ) {
var chekbox = listItems[i].getElementsByTagName("input")
//console.log(chekbox)
}
}
.completedItem {
color: gray;
text-decoration: line-through;
}
<form name="myform">
Enter a note: <br/>
<input type="text" name="inputbox">
<input type="button" name="button" Value="Add" onClick="createNote(this.form)">
</form>
<main>
<h2>Task List: </h2>
<ul id="abc" onchange="grayCheckedItems(this.ul)">
</ul>
</main>
Ответ №2:
измените выходной html в li на
<input type="checkbox"/><label>Test</label>
и этот css
input[type=checkbox]:checked label {
color: gray;
}
Ответ №3:
Не используйте встроенный JS, это делает ваш HTML уродливым и имеет некоторые недостатки, вот более короткий ответ
document.querySelector("#abc").onchange = function(e) {
let textElement = e.target.previousElementSibling;
e.target.checked ? textElement.classList.add("done") :
textElement.classList.remove("done");
};
document.querySelector("input[name='button']").onclick = function() {
document.querySelector("#abc").innerHTML = `
<li><span>${this.previousElementSibling.value}</span> <input type="checkbox"></li>
`;
}
span.done {
color: gray;
text-decoration: line-through;
}
<form name="myform">
Enter a note: <br/>
<input type="text" name="inputbox">
<input type="button" name="button" Value="Add">
</form>
<main>
<h2>Task List: </h2>
<ul id="abc">
</ul>
</main>