LocalStorage
- đây là một API giúp bạn lưu trữ các dữ liệu (ở dạng String hoặc Number) theo cấu trúc Key-Value xuống dưới bộ nhớ của trình duyệt, dữ liệu này sẽ không bị xóa kể cả bạn có tải lại trang. Bạn sẽ viết vào một file storage.js
hai hàm:saveToStorage
: Hàm nhận hai tham số là Key và Value, sau đó sẽ thực hiện việc lưu xuống LocalStorage.getFromStorage
: Hàm nhận vào tham số là Key, sau đó sẽ lấy dữ liệu từ LocalStorage theo Key tương ứng.script/storage.js
"use strict"; // Lấy danh sách thú cưng đã có trong localStorage /** * Hàm thực hiện việc Lưu trữ vào LocalStorage * @param {*} key Từ khóa * @param {*} value Giá trị */ function saveToStorage(key, value) { var data = value; // Kiểm tra, nếu dữ liệu là kiểu mảng ARRAY // -> cần phải convert về kiểu String để lưu trữ được vào LocalStorage if(Array.isArray(value)) { // Hàm JSON.stringify sẽ chuyển đổi ARRAY thành STRING data = JSON.stringify(value); } // Lưu trữ vào LocalStorage với từ khóa "key" window.localStorage.setItem(key, data); } /** * Hàm lấy giá trị được lưu trữ trong LocalStorage * @param {*} key Từ khóa */ function getFromStorage(key) { // Lấy dữ liệu từ LocalStorage return window.localStorage.getItem(key); }
script.js
// Bắt sự kiện Click vào nút "Submit" btnSubmit.addEventListener("click", function () { // Lấy dữ liệu từ các Input Form const inputId = document.getElementById("input-id").value; const inputName = document.getElementById("input-name").value; const inputAge = parseInt(document.getElementById("input-age").value); const inputType = document.getElementById("input-type").value; const inputWeight = parseInt(document.getElementById("input-weight").value); const inputLength = parseInt(document.getElementById("input-length").value); const inputColor = document.getElementById("input-color-1").value; const inputBreed = document.getElementById("input-breed").value; const inputVaccinated = document.getElementById("input-vaccinated").checked; const inputDewormed = document.getElementById("input-dewormed").checked; const inputSterilized = document.getElementById("input-sterilized").checked; const data = { id: inputId, name: inputName, age: inputAge, type: inputType, weight: inputWeight, length: inputLength, color: inputColor, breed: inputBreed, vaccinated: inputVaccinated, dewormed: inputDewormed, sterilized: inputSterilized, date: new Date(), }; // Validate dữ liệu hợp lệ if (data.id === "") { alert("Please input for pet id!"); return false; } for (let i = 0; i < petArr.length; i++) { if (data.id === petArr[i].id) { alert("ID must unique!"); return false; } } if (data.name === "") { alert("Please input for pet name!"); return false; } if (data.age === "" || isNaN(data.age)) { alert("Please input for age!"); return false; } else if (data.age < 1 || data.age > 15) { alert("Age must be between 1 and 15!"); return false; } if (data.type === "Select Type") { alert("Please select type!"); return false; } if (data.weight === "" || isNaN(data.weight)) { alert("Please input for weight!"); return false; } else if (data.weight < 1 || data.weight > 15) { alert("Weight must be between 1 and 15!"); return false; } if (data.length === "" || isNaN(data.length)) { alert("Please input for length!"); return false; } else if (data.length < 1 || data.length > 100) { alert("Length must be between 1 and 100!"); return false; } if (data.breed === "Select Breed") { alert("Please select Breed"); return false; } petArr.push(data); renderTableData(petArr); resetForm(); // Lưu trữ dữ liệu Danh sách Pet array vào LocalStorate với key="petData" // Gọi hàm vừa viết trong file "script/storage.js" saveToStorage("petData", petArr); });
script.js
// Xóa một thú cưng function deletePet(x) { if (confirm("Are you sure?")) { for (let i = 0; i < petArr.length; i++) { if (petArr[i].id === x) { petArr.splice(i, 1); renderTableData(petArr); // Sau khi xóa dòng dữ liệu -> tiến hành cập nhập lại dữ liệu trong LocalStorage // Lưu trữ dữ liệu Danh sách Pet array vào LocalStorate với key="petData" // Gọi hàm vừa viết trong file "script/storage.js" saveToStorage("petData", petArr); } } } }
script.js
// Hiển thị danh sách Pet Data đã lưu trữ trong LocalStorage ngay khi vừa load xong trang web // Do dữ liệu lưu trữ trong LocalStorage chỉ là String -> nên cần convert sang Array để hiển thị // Sử dụng hàm JSON.parse('string') -> sẽ chuyển từ string sang array var dataString = getFromStorage("petData"); var dataArr = JSON.parse(dataString); petArr.splice(0, petArr.length); // Clear toàn bộ PetArr trước khi render lại table for (let i = 0; i < dataArr.length; i++) { let pet = dataArr[i]; pet.date = new Date(pet.date); // Add vào petArr petArr.push(pet); } renderTableData(petArr); // Hiển thị lại Table
Download source code đã giải bài tập đầy đủ
: asm2_dagiaiCùng nhau học tập, khám phá các kiến thức nền tảng về Lập trình web, mobile, database nhé.
Nền tảng kiến thức - Hành trang tới tương lai hân hạnh phục vụ Quý khách!
Khám phá, trải nghiệm ngay
Vui lòng đăng nhập để gởi bình luận!
Đăng nhậpChưa có bình luận nào!