개발
[JS] localStorage 이용하기
사과넹
2020. 10. 22. 21:26
with Nicolas.
input 창에 이름을 입력하고 localStorage에 저장해서 새로고침해도 입력한 이름을 기억하게 해보자.
코딩순서
1. 구조짜기 - form 과 자식요소로 input 생성
이름 입력 후 뜨는 text를 띄우기 위한 글자태그 생성(h, p 등)
2. 변수선언 - 구조로 만든 것들 모두 변수 선언하기
3. 함수선언
1) 이름 입력시 띄우는 메시지 함수
2) 엔터시 새로고침되는 이벤트를 중지하는 함수
3) 이름이 입력되지 않았을 때 계속 form창을 유지하게 하는 함수
4) if구문을 넣은 함수(저장된 이름이 없을시 3번함수, 있을시 1번함수)
5) localStorage에 이름을 저장하는 함수(setItem메소드 이용)
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Something</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form class="js-form form">
<input type="text" placeholder="What's your name?" />
</form>
<h4 class="js-greeting greeting"></h4>
</body>
<script src="greeting.js"></script>
</html>
Javascript
const form = document.querySelector('.js-form');
const input = form.querySelector('input');
const greeting = document.querySelector('.js-greeting');
const USER_LS = 'currentUser',
SHOWING_CN = 'showing';
function saveName(text){
localStorage.setItem(USER_LS,text);
}
function handleSubmit(event){
event.preventDefault();
const currentValue = input.value;
paintGreeting(currentValue);
saveName(currentValue);
}
function askForName(){
form.classList.add(SHOWING_CN);
form.addEventListener('submit',handleSubmit);
}
function paintGreeting(text){
form.classList.remove(SHOWING_CN);
greeting.classList.add(SHOWING_CN);
greeting.innerText = `HELLO ${text}`
}
function loadName(){
const currentUser = localStorage.getItem(USER_LS);
if(currentUser === null){
askForName();
} else{
paintGreeting(currentUser);
}
}
function init(){
loadName();
}
init();
영상을 한번보고, 두번째로보며 코드를 작성하면서 했는데도 오류가 나서 너무 당황했다.
하지만 역시 내 잘못이였지.
순서대로 이해하면서 코드리딩을하니 어느부분이 잘못되었는지 찾을 수 있었다.
개발자의 길은 멀다 ..
728x90
반응형