我正在整理一份 list ,我希望最终将其变成一本武术“杂志”。目前,我的删除键有一个单击功能,可以删除 DOM 元素。但是,我不确定如何删除存储在对象中的数据
var curBelt = $('#belt').val();
//This is my data object that holds the array per belt
var data = {
white: [],
blue: [],
purple: [],
brown: [],
black: [],
}
//This is my list
var $list = $('#todoList');
//This is a change function that take the value of the belt and runs the createListFromData function
//to reapply the svaed data in the array
$('#belt').change(function(){
curBelt = $(this).val();
createListFromData();
});
//This function adds the checkbox, itemtext, and the click function to cross off items
function addNewItem (itemKey, itemText) {
var $listItem = $('<li>');
var $span = $('<span>' + itemKey + ' - '+ itemText +'</span>');
var $editButton = $('<button id = "editButton">Edit</button>')
var $deleteButton = $('<button id = "deleteButton">Delete</button>')
$listItem.append($span);
$list.append($listItem);
$list.append($editButton);
$list.append($deleteButton);
$deleteButton.click(function() {
$listItem.remove();
$editButton.remove();
$deleteButton.remove();
});
}
var totalItems = 0;
var $inItemText = $("#inItemText");
var $itemKey = $("#itemKey");
console.log($itemKey);
$itemKey.focus();
//This uses enter to push the text to my belt arrays and calls the addsNewItem function to the list
$inItemText.on('keyup', function (event) {
if (event.which === 13) {
totalItems++;
var inputObject = {};
var itemText = $(this).val();
var itemKey = $itemKey.val();
if (!itemText || itemText === "") {
return false;
}
inputObject.move = itemKey;
inputObject.note = itemText;
data[curBelt].push(inputObject);
console.log(data);
addNewItem(itemKey, itemText);
$(this).val('');
$itemKey.val('');
inItemText.focus();
}
});
//This empties the list and reapplies the arrays in the data object
var createListFromData = function () {
$list.empty();
data[curBelt].forEach(function (object) {
addNewItem (object.move, object.note);
});
}
createListFromData();
感谢任何帮助!
最佳答案
我要做的第一件事就是将 totalItems++;
向下移动到
if (!itemText || itemText === "") {
返回假;
}
如果它是空白元素,这将阻止您添加到总数中。我也不确定为什么您要在 addNewItem 函数中初始化删除点击事件。你介意制作一个 jsfiddle 或 codepen 来审阅吗?
关于javascript - 如何使用单击功能删除对象中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772181/