在这个JavaScript代码中就像你可以通过id删除项目而且它太长了我想要更短的东西。所以我想按一个按钮删除所有项目。我试图编辑它,但我总是失败。
JavaScript代码:
var currentFormVisibilityStatus = false;
function SaveNotes() {
var category = document.getElementById("slSearchCategory").value;
var todo = document.getElementById("txtToDo").value;
if (category == "") {
alert("Please select Category.");
return;
}
var storage = JSON.parse(localStorage.getItem('ToDoList'));
var arrayLength = storage.length;
storage[arrayLength] = category;
storage[arrayLength + 1] = todo;
localStorage.setItem('ToDoList', JSON.stringify(storage));
category = "";
loadNotes();
clearNote();
}
function clearNote() {
var todo = document.getElementById("txtToDo");
todo.value = '';
}
function loadNotes() {
var storage = JSON.parse(localStorage.getItem('ToDoList'));
if (!storage) {
storage = [];
localStorage.setItem('ToDoList', JSON.stringify(storage));
}
var displayArea = document.getElementById("displayArea");
var currentFilter = document.getElementById("slSearchCategory").value;
var innerDiv = "";
for (var i = storage.length - 1; i >= 0; i = i - 2) {
if (currentFilter == storage[i - 1] || currentFilter == "") {
var todoColor = 'ffffff';
switch (storage[i - 1]) {
case 'Sales':
todoColor = 'ffffff';
break;
default:
todoColor = 'ffffff';
break;
}
innerDiv += "<div class='displayToDo' style='background:#" + todoColor + "'><input type='image' src='delete.png' width='15px' height='15px' onclick='removeMe(" + i + ")' /> " + storage[i] + "</div>"+ "</br>";
}
}
if (innerDiv != undefined) {
displayArea.innerHTML = innerDiv;
}
else {
displayArea.innerHTML = "";
}
}
function removeMe(itemId) {
var storage = JSON.parse(localStorage.getItem('ToDoList'));
storage.splice(itemId - 1, 2);
localStorage.setItem('ToDoList', JSON.stringify(storage));
loadNotes();
}
onload = function () {
loadNotes();
ShowHideForm();
}
Html代码:
<div class="headerDiv">
<span>Category :</span>
<select id="slSearchCategory" class="textBox" onchange="loadNotes()" style="width: 100px">
<option value="" selected="selected">All ToDo</option>
<option value="Personal">Personal</option>
<option value="HR">HR Query</option>
<option value="Payroll">Payroll</option>
<option id="Sales" value="Sales">Sales</option>
</select>
<span style="padding-left: 20px">Todo : </span>
<textarea id="txtToDo" class="textBox" rows="2" cols="20" style="width: 300px"></textarea>
<input type="button" onclick="SaveNotes()" name="Submit" class="submitButton" title="Submit"
value="Add Todo" />
</div>
<div id="displayArea">
</div>
<input type="button" onclick="removeAll();" value="Remove all"/>
答案 0 :(得分:1)
您可以创建一个新功能并使用onclick事件调用它
HTML代码
<input type="button" value="Remove all" onclick="removeAll();"/>
JavaScript函数
function removeAll(){
var storage = JSON.parse(localStorage.getItem('ToDoList'));
storage.length=0;
localStorage.setItem('ToDoList', JSON.stringify(storage));
loadNotes();
}
另请查看How do I empty an array in JavaScript?,以便了解如何以正确的方式清空数组