출처
- Nomad Academy
www.youtube.com/watch?v=wUHncG3VwPw&list=PL7jH19IHhOLM8YwJMTa3UkXZN-LldYnyK
#3.3-3.4 Saving the User Name part 1-2
1). 기본개념
- local storage
: 작은 정보를 개발자 유저 컴퓨터에 저장하는 방법이다.
- localStorage.setItem("key", value);
local storage에 데이터 입력하기
- localStorage.getItem("key", value);
local storage에서 데이터 가져오기
- form을 제출하는 event가 발생하면
document까지 가서 다른 곳으로 그 데이터가 이동한다.
그리고 페이지는 새로고침이 된다. : 이것이 event의 defalut상태임.
- 새로 생성한 함수일수록 위쪽에 배치한다.
2). 과정
html짜기
<body>
<form class="js-form form">
<input type="text" placeholder="What is your name?" />
</form>
<h4 class="js-greetings greetings"></h4>
</body>
form: 데이터 입력 양식을 감싸주는 태그
CSS짜기
.form,
.greetings {
display: none;
}
.showing {
display: block;
}
최종 함수짜기
function init() {
loadName();
}
init();
함수를 실행시켜 원하는 데이터를 저장할 것이다.
변수짜기
const form = document.querySelector(".js-form"),
input = form.querySelector("input"),
greeting = document.querySelector(".js-greetings");
꼭 써줘야 하는건 아니라고 하시지만 안짜면
저 코드 다 일일히 써줘야 하니까 써준다.
함수_1 value 값 불러오는
const USER_LS = "currentUser";
function loadName() {
const currentUser = localStorage.getItem(USER_LS);
if(currentUser === null){
} else {
}
}
함수_2 입력했던 이름을 html에 넣어주는
function paintGreeting(text) {
greeting.innerText = `Hello ${text}`;
}
입력한 이름을 매개변수 text로 집어넣는다.
함수_1.2 value값 불러오는 + 함수2 추가
const USER_LS = "currentUser";
function loadName() {
const currentUser = localStorage.getItem(USER_LS);
if(currentUser === null){
} else {
paintGreeting(currentValue);
}
}
함수_2.2 클래스 속성을 추가하는 + 입력했던 이름을 html에 넣어주는
SHOWING_CN = "showing";
function paintGreeting(text) {
form.classList.remove(SHOWING_CN);
greeting.classList.add(SHOWING_CN);
greeting.innerText = `Hello ${text}`;
}
함수_1.3 value값 불러오는 + 함수2 추가
const USER_LS = "currentUser";
function loadName() {
const currentUser = localStorage.getItem(USER_LS);
if(currentUser === null){
} else {
paintGreeting(currentValue);
}
}
함수_3 value를 물어보는
function askForName() {
form.classList.add(SHWING_CN);
form.addEventListener("submit", handleSubmit);
}
함수_4 value를 물어보는 + 함수2추가
function handleSubmit(event){
event.preventDefalut();
const currentValue = input.value;
paintGreeting(currentValue);
}
함수_5 value를 저장하는
function saveName(text){
localStorage.setItem(USER_LS, text);
}
함수_4.2 value를 물어보는 + 함수2추가 + 함수5추가
function handleSubmit(event){
event.preventDefalut();
const currentValue = input.value;
paintGreeting(currentValue);
saveName(currentValue);
}
'JavaScript' 카테고리의 다른 글
[JavaScript] 연산자 (operator) (0) | 2021.03.23 |
---|---|
[JavaScript] Nomad Academy, 바닐라 JS로 크롬 앱 만들기 - to do list만들기 / 20.06.08 (0) | 2020.06.08 |
[JavaScript] Nomad Academy, 바닐라 JS로 크롬 앱 만들기 - 시계만들기 / 20.06.05 (0) | 2020.06.05 |
[JavaScript] DOM - 제어 대상 찾기 (0) | 2020.06.05 |
[JavaScript] BOM (Browser Object Model) (0) | 2020.06.05 |