У меня есть небольшое приложение, которое добавляет элементы в список. Элементы появляются рядом с ними рядом с кнопкой, чтобы я мог нажимать эту кнопку, чтобы добавить текст (text-decoration: line-through). Я пробовал несколько разных вещей, но ничего не работает (Javascript для добавления элементов, удаления последнего элемента, добавления классов в новые элементы li и т. Д. Все это прекрасно работает, моя проблема связана только с частью JQuery, больше комментариев на самом коде).HTML-список, добавление JQuery для перехода к выбранному элементу.
HTML
<html>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button id="remove"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Js/Jq:
document.getElementById("add").addEventListener('click', function() {
var check = document.createElement("button");
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
var buttonText = document.createTextNode("Check");
newEl.className = "liEl";
newEl.appendChild(newText);
newEl.appendChild(check);
check.setAttribute("class", "checked");
check.appendChild(buttonText);
/* Problem starts here */
$("button.checked").on('click', function() {
$('li.liEl').css('text-decoration: line-through');
/* It should get the button with the class "checked" and on click, make the li elements with class "liEl" to have that css... */
}
);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
document.getElementById('input').onkeypress = function(e) {
if (e.keyCode == 13) {
document.getElementById('add').click(); /* adds an event listener to the submit text, keyCode 13 equals the enter key so when it's pressed it presses the add button. */
}
}
});
/* Delete last item function: */
document.getElementById("remove").addEventListener('click', function() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el, If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
});
Ваше использование .css(), вероятно, неправильно. Начните отсюда: http://api.jquery.com/css/#css2 – Chiu
Это работает, но странно, только когда в список добавлено более 1 элемента (я знал, что он пересечет их всех, но не знаю, почему это не может применить эффект, когда есть только 1 элемент). – Sergi
@Sergi Это потому, что ваша функция click добавлена до добавления нового элемента в DOM. Таким образом, функция вступает в силу после добавления другого элемента. – Dfirmansyah