javascript - Splice() 方法删除不在索引处的数组末尾
问题描述
我的功能removeItems()
是从 li 元素中的列表项中删除项目。目前我可以从视图中删除该项目,但数组拼接方法会从数组末尾而不是索引处删除元素。
我的代码是:
var data = [
"Tuesday ",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
function itemArray(ele) {
let items = '';
for (let i = 0; i < ele.length; i++) {
items += `<li>${ele[i]} <button type='button' class='removeItem'>Remove Item</button> </li>`;
}
return items;
}
function addItemFunction () {
const addButton = document.getElementById('addButton');
const input = document.getElementById('input').value;
data.push(input);
htmlInside(data);
}
function removeItemFunction() {
data.pop(data);
htmlInside(data);
}
function removeItems() {
const listUl = main.querySelector('ul');
listUl.addEventListener('click', (event) => {
if (event.target.tagName == 'BUTTON') {
let li = event.target.parentNode;
let ul = li.parentNode;
ul.removeChild(li);
var index = data.indexOf(data);
data.splice(index, 1);
console.log(data);
}
});
}
function htmlInside(data) {
let getHtml = `
<ul class="listItems">
${itemArray(data)}
</ul>
<input type='input' id='input' required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
`
document.querySelector('.hero').innerHTML = getHtml;
addButton.addEventListener('click', function () {
addItemFunction();
});
removeButton.addEventListener('click', function () {
removeItemFunction();
});
removeItems();
}
我认为我没有正确找到数据的索引。可能是一个问题var index = data.indexOf(this); data.splice(index, 1);
当我console.log(index)
记录-1。
解决方案
问题是在这一行中var index = data.indexOf(data)
,您正在检查数据的索引,您应该检查数据数组中元素的索引,因此您应该首先从列表中获取该元素 ele=li.textContent
,然后将其传递给data.indexOf(ele)
推荐阅读
- ios - 以 RTL 语言翻转的 SwiftUI 菜单内容
- migration - Bigcommerce 订单是否有其他详细信息和订单项属性
- android - android - 如何更改底部导航文本
- javascript - 从 discord.js 中的传入消息中获取命令
- javascript - Google 表格 - 脚本编辑器 数据验证生成器 - 格式化过滤日期列表
- php - 如何选择在 table1 中有值但在 table2 中为 NULL 的字段表?
- python - 模拟 NamedTemporaryFile 写入和关闭文件
- php - Hypens 打破 Laravel 动态路由
- powerbi - 在 Power Query 中应用条件(根据每个 Consol ID 筛选最早日期) - PowerBI
- tkinter - Tkinter 通过循环将条目值添加到列表中