我正在从 SuperSimpleDev 的教程学习 JS,但遇到了困难。 我对 splice() 的功能感到困惑。在网上我只找到 splice() 干净地删除元素的例子。但它却给我留下了空字符串。
我有一个待办事项元素数组,每个待办事项元素旁边都有一个删除按钮,单击该按钮后,该按钮应与待办事项文本一起消失。拼接后,我在控制台上记录了我的数组,发现我只剩下 [todo1, '', '', todo4] 等等。因此,即使我已经拼接了这些元素,删除按钮仍然显示(在我不知道的空字符串元素旁边)。 左侧删除按钮:
function renderTodoList() {
const inputElement = document.querySelector('.js-name-input');
const name = inputElement.value;
todoList.push(name);
let todoListHTML = '';
for(let i=0; i<todoList.length; i++){
const todo = todoList[i];
const html = `
<p>
${todo}
<button onclick="
todoList.splice(${i},1);
renderTodoList();
">Delete</button>
</p>
`;
todoListHTML += html;
}
console.log(todoListHTML);
document.querySelector('.js-display-todo').innerHTML = todoListHTML;
inputElement.value = '';
console.log(todoList);
}
这是我给你的一些想法..
function rendertodolist(){
const inputElement = document.querySelector(".js-name-input");
const name = inputElement.value;
todoList.push(name);
let todoListHTML = '';
for(let i=0; i<todoList.lenght; i++){
const todo = todoList[i];
const html =`
<p>
${todo}
<button onclick="
todoList = todoList.filter((_, index) => index !== ${i});
renderTodoList();
">Delete</button>
</p>
`;
todoListHTML +=html;
}
console.log(todoLISTHTML);
document.querySelector('.js-display-todo').innerHTML = todoListHTML;
inputElement.value = '';
console.log(todoList);
}