我们将创建一个网站,该网站将记录我们的笔记并使用 HTML、CSS 和 JavaScript 保存它们以备将来使用。
先决条件:
- 基本了解 HTML、Bootstrap 和 JavaScript。
方法:
- HTML:我们将使用 HTML 创建网站的基本框架。
- Bootstrap:与 CSS 相比,使我们的工作更轻松。所以我们使用了 Bootstrap 来美化我们的框架。
- JavaScript:保存和删除笔记的基本逻辑在 index.js 文件中。
示例:在这里,我们首先设计项目的结构,然后我们将为功能编写代码。
index.html
Take your Notes here
Add a Note
Your Notes
index.js
showNotes();
// If user adds a note, add it to the localStorage
let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function(e) {
let addTxt = document.getElementById("addTxt");
let notes = localStorage.getItem("notes");
if (notes == null) notesObj = [];
else notesObj = JSON.parse(notes);
notesObj.push(addTxt.value);
localStorage.setItem("notes", JSON.stringify(notesObj));
addTxt.value = "";
showNotes();
});
// Function to show elements from localStorage
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) notesObj = [];
else notesObj = JSON.parse(notes);
let html = "";
notesObj.forEach(function(element, index) {
html += `
Note ${index + 1}
${element}
`;
});
let notesElm = document.getElementById("notes");
if (notesObj.length != 0) notesElm.innerHTML = html;
else
notesElm.innerHTML = `Nothing to show!
Use "Add a Note" section above to add notes.`;
}
// Function to delete a note
function deleteNote(index) {
let notes = localStorage.getItem("notes");
if (notes == null) notesObj = [];
else notesObj = JSON.parse(notes);
notesObj.splice(index, 1);
localStorage.setItem("notes",
JSON.stringify(notesObj));
showNotes();
}
索引.js
showNotes();
// If user adds a note, add it to the localStorage
let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function(e) {
let addTxt = document.getElementById("addTxt");
let notes = localStorage.getItem("notes");
if (notes == null) notesObj = [];
else notesObj = JSON.parse(notes);
notesObj.push(addTxt.value);
localStorage.setItem("notes", JSON.stringify(notesObj));
addTxt.value = "";
showNotes();
});
// Function to show elements from localStorage
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) notesObj = [];
else notesObj = JSON.parse(notes);
let html = "";
notesObj.forEach(function(element, index) {
html += `
Note ${index + 1}
${element}
`;
});
let notesElm = document.getElementById("notes");
if (notesObj.length != 0) notesElm.innerHTML = html;
else
notesElm.innerHTML = `Nothing to show!
Use "Add a Note" section above to add notes.`;
}
// Function to delete a note
function deleteNote(index) {
let notes = localStorage.getItem("notes");
if (notes == null) notesObj = [];
else notesObj = JSON.parse(notes);
notesObj.splice(index, 1);
localStorage.setItem("notes",
JSON.stringify(notesObj));
showNotes();
}
输出: