목록에 항목을 추가하는 작은 앱이 있습니다. 항목 옆에 단추가 표시되며 해당 단추를 눌러서 (텍스트 장식 : 줄 넘김)을 추가 할 수있게하려고합니다. 나는 몇 가지 시도했지만 아무것도 작동하지 않는 것 (항목을 추가하는 자바 스크립트, 마지막 항목을 삭제하고 새로운 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);
});
귀하의 사용은() 아마 잘못된 것입니다. 여기에서 시작하십시오 : http://api.jquery.com/css/#css2 – Chiu
이상하지만 이상하게도 작동합니다. 목록에 1 개 이상의 항목이 추가되었을 때만 가능합니다. 한 항목 만있는 경우 효과를 적용 할 수 없습니다). – Sergi
@Sergi DOM에 새 요소가 추가되기 전에 클릭 기능이 추가 되었기 때문입니다. 따라서 다른 항목을 추가하면 기능이 적용됩니다. – Dfirmansyah