반응형
웹강의에서 localstorage를 사용해서 프로젝트를 개발하라는 말을 듣고.... 예제를 공부해봤다.
프로그램에서는 돌아가는데 티스토리에다가 올리니깐 초기화 버튼이 안먹는당. 공부를 더 해봐야겠다.
<HTML>
localStorage 연습
<코드>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vanilla JavaScript</title>
<style>
p { height: 50px; width: 50%; font-size: 24px; border-radius: 10px;}
button { background-color: lightcoral; border: none; height: 30px; width: 100px; border-radius: 10px;}
</style>
</head>
<body>
<h1>localStorage 연습</h1>
<hr>
<form class="myform">
<input type="text" placeholder="하고싶은말 작성하기">
</form>
<p class="outtxtz"></p>
<button>초기화</button>
<script>
const form = document.querySelector(".myform"),
input = form.querySelector("input"),
outtxt = document.querySelector(".outtxtz"),
button = document.querySelector("button");
const LOCAL_DATA = "inputtxt";
function hiddeninput(name) {
outtxt.style.display = "block";
form.style.display = "none";
button.style.display = "block";
button.addEventListener("click", onClick);
outtxt.innerText = `HTML 공부중입니다. 저는 ${name} 라고 생각합니다. `;
}
function seeinput() {
form.style.display = "block";
outtxt.style.display = "none";
button.style.display = "none";
form.addEventListener("submit", onSubmit);
}
function onClick() {
localStorage.removeItem(LOCAL_DATA);
console.log("js");
loaded();
}
function onSubmit(e) {
e.preventDefault();
localStorage.setItem(LOCAL_DATA, input.value);
hiddeninput(input.value);
input.value = "";
}
function loaded() {
const data = localStorage.getItem(LOCAL_DATA);
if (data === null) {
seeinput();
} else {
hiddeninput(data);
}
}
function init() {
loaded();
}
init();
</script>
</body>
</html>
반응형
'Language > HTML, JS' 카테고리의 다른 글
[HTML, JS] 두개의 주사위 눈의 합 경우의 수 (0) | 2022.10.20 |
---|---|
[HTML, JS] DIV와 List를 이용한 문서의 동적 구성 (0) | 2022.10.18 |
[HTML, JS] innerHTML 활용 (2) | 2022.10.18 |