JSONPlaceholder를 사용하여 할 일 목록을 만들고 있습니다. 모든 것이 제대로 작동하지만 (적어도 현재는) 선택한을 삭제 <li>
하면 다음 항목 <li>
이 삭제됩니다.
나는하여했기 때문에 그것이 알고 .splice(id - 1, 1)
에서 deleteTodo
. 대신 선택한 항목의 ID를 가진 항목의 올바른 인덱스를 가져와야한다는 것을 알고 selectedItem
있지만 가져 오는 방법을 모르겠습니다. 아마도 사용해야 할 것 findIndex()
같지만 매개 변수로 줄 함수를 생각할 수 없습니다.
어떤 도움을 주시면 감사하겠습니다.
todoList = {
todos: [],
removeClick: function (icon) {
let selectedIndex = icon.parentElement.parentElement.dataset.index;
todoList.deleteTodo(selectedIndex);
},
deleteTodo: function (index) {
var id = index;
$.ajax({
url: `https://jsonplaceholder.typicode.com/todos/${id}`,
type: 'delete',
success: function () {
todoList.todos.splice(id - 1, 1);
todoList.displayTodo();
}
})
},
displayTodo: function () {
$ul.innerHTML = "";
let innerContents = '';
for (let i = 0; i < this.todos.length; i++) {
let todo = this.todos[i];
let className = 'completed'
let checked = 'checked'
if (todo.completed === false) {
className = "";
checked = "";
}
innerContents += `
<li data-index="${todo.id}">
<div class="checkboxDiv">
<input type="checkbox" class="checkbox" data-key="checkbox"
${checked} />
</div>
<div class="contents ${className}" data-key="contents">
${todo.title}
</div>
<div class="icondiv">
<i class="far fa-edit" data-key="icon_edit"></i>
<i class="far fa-trash-alt" data-key="icon_trash"></i>
</div>
</li>
`;
}
$ul.innerHTML = innerContents;
}
};
todoList.getData();
$ul.addEventListener('click', (e) => {
switch (e.target.dataset.key) {
case "icon_trash":
todoList.removeClick(e.target);
break;
}
});
해결책:
참고 : 코드 스 니펫 아래에서 코드 관련 문제를 설명했습니다.
삭제 된 항목으로 데이터를 간단히 필터링 할 수 있습니다.
todoList.todos = todoList.todos.filter(({id: todoID}) => todoID !== id);
또는
todoList.todos.splice(todoList.todos.findIndex(({id: todoID}) => todoID == id), 1);
id - 1
배열 인덱스가 아니기 때문에 하지 마세요. todo의 id 값입니다.
휴지통 아이콘 자체에 클릭 이벤트 추가
<i class="fa fa-trash" data-key="icon_trash" onclick="todoList.removeClick(this)"></i></div>
아래는 작동 코드 스 니펫입니다 (스크립트에 많은 오류가 있습니다. 어떻게 작동하는지 모르겠습니다.))
var $ul = $('ul');
todoList = {
todos: [],
removeClick: function(element) {
let id = $(element).parent().parent().data('index');
todoList.deleteTodo(id);
},
deleteTodo: function(id) {
$.ajax({
url: `https://jsonplaceholder.typicode.com/todos/${id}`, //
type: 'delete',
success: function() {
// todoList.todos = todoList.todos.filter(({id: todoID}) => todoID !== id);
todoList.todos.splice(todoList.todos.findIndex(({id: todoID}) => todoID == id), 1);
todoList.displayTodo();
}
})
},
getTodos: function() {
$.ajax({
url: `https://jsonplaceholder.typicode.com/todos/`, //
type: 'get',
success: function(data) {
todoList.todos = data;
todoList.displayTodo();
}
})
},
displayTodo: function() {
$ul.innerHTML = "";
let innerContents = '';
for (let i = 0; i < todoList.todos.length; i++) {
let todo = todoList.todos[i];
let className = 'completed'
let checked = 'checked'
if (todo.completed === false) {
className = "";
checked = "";
}
innerContents += `<li data-index="${todo.id}"><div class="checkboxDiv">
<input type="checkbox" class="checkbox" data-key="checkbox" ${checked}/></div>
<div class="contents ${className}" data-key="contents">
${todo.title}</div>
<div class="icondiv"><i class="fa fa-edit" data-key="icon_edit"></i>
<i class="fa fa-trash" data-key="icon_trash" onclick="todoList.removeClick(this)"></i></div>
</li>`
}
$ul.html(innerContents);
},
}
todoList.getTodos();
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul></ul>
문제 : 아래의 객체 배열 고려
[{id: 1, name: 'name 1'},{id: 2, name: 'name 2'},{id: 3, name: 'name 3'},{id: 4, name: 'name 4'}]
코드로 todoList.todos.splice(id - 1, 1);
ID가 2 인 항목을 삭제하자 (이름 = '이름 2')는 todoList.todos.splice(2 - 1(1), 1);
. 따라서 인덱스 1에서 항목을 올바르게 삭제하고 새 개체는
[{id: 1, name: 'name 1'},{id: 3, name: 'name 3'},{id: 4, name: 'name 4'}]
이제 ID가 3 (name = 'name 3') 인 항목을 삭제하겠습니다 todoList.todos.splice(3 - 1(2), 1);
.
여기에 코드 문제가 있습니다. 이제 인덱스 2에있는 항목이 삭제 {id: 4, name: 'name 4'}
되고 새 개체가
[{id: 1, name: 'name 1'},{id: 3, name: 'name 3'}]
설명:
findIndex(({id: todoID}) => todoID == id)
todo
에서 객체를 findIndex
, 난 그냥 단지 잡고 있어요 id
에서 속성을 todo
객체와로 이름을 변경todoID
id
하기 todoID
위해 로 이름 을 변경 했습니다.id
deleteTodo
todoID
으로 id
이는 deleteTodo
방법의 매개 변수findIndex
반환 합니다.index
todo
Array.splice(<returned index>, 1)
제거합니다.todo
없이 Object destructuring
하고 arrow function
, 코드 외모는 다음과 같은
todoList.todos.splice(todoList.todos.findIndex(function(todo) {
return todo.id === id;
}), 1);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다