我想从一个数组中删除一个项目,所以我想先得到项目的id,这样我就可以知道要删除的索引了.我有这段代码来自一个todo应用。
// Generate a todo
const generateTodo = function () {
todoTemplate = '<li id="%id%">%todo% <span onclick="removeTodo()" class="close">x</span></li>'
newTodo = todoTemplate.replace('%todo%', filters.searchText)
newTodo = newTodo.replace('%id%', todos.length)
document.querySelector('.todos').insertAdjacentHTML('beforeend', newTodo)
document.querySelector('.add-todo').value = ''
// adding the todo to the array
todos.push(newTodo)
}
我的问题是: 我如何才能从我点击的 "li "中返回id?
而不是创建动态ID(这是一个代码气味),也不是使用内联处理程序(这是 问题多多,不值一提),考虑用 createElement
而不是--然后你可以使用Javascript将一个事件监听器正确地附加到它上面。
const generateTodo = function() {
const li = document.querySelector('.todos').appendChild(document.createElement('li'));
li.textContent = filters.searchText + ' ';
const span = li.appendChild(document.createElement('span'));
span.textContent = 'x';
span.className = 'close';
span.onclick = () => li.remove();
document.querySelector('.add-todo').value = ''
todos.push(filters.searchText);
}