<투 두 리스트 만들기> <= 꼼꼼히 다시 보기 !
const toDoForm = document.querySelector("#todo-form");
const toDoInput = toDoForm.querySelector("input");
const toDoList = document.querySelector("#todo-list");
const TODOS_KEY ="todos";
let toDos = [];
function saveToDos() {
localStorage.setItem(TODOS_KEY, JSON.stringify(toDos));
}
function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
toDos = toDos.filter((toDo) => toDo.id !== parseInt(li.id));
saveToDos();
}
function paintToDo(newTodo) {
const li = document.createElement("li");
li.id = newTodo.id;
const span = document.createElement("span");
span.innerText = newTodo.text;
const button = document.createElement("button");
button.innerText = "❌";
button.addEventListener("click", deleteToDo);
li.appendChild(span);
li.appendChild(button);
toDoList.appendChild(li);
}
function handleToDoSubmit(event) {
event.preventDefault();
const newTodo = toDoInput.value;
/// input의 현재 value를 새로운 변수에 복사
toDoInput.value = "";
const newTodoObj = {
text: newTodo,
id: Date.now(),
};
toDos.push(newTodoObj);
paintToDo(newTodoObj);
saveToDos();
}
toDoForm.addEventListener("submit", handleToDoSubmit);
const savedToDos = localStorage.getItem(TODOS_KEY);
if (savedToDos !== null) {
const parsedToDos = JSON.parse(savedToDos);
toDos = parsedToDos;
parsedToDos.forEach(paintToDo);
}
- const toDoInput = toDoForm.querySelector("input");
const toDoInput = document.querySelector("#todo-form input");
위 두 코드가 하는 일은 같다.
- JSON.stringify()는 어떤 JavaScript 코드든 string으로 만들어 준다.
즉, 활용할 수 있는 array를 얻게 해줌.
- forEach는 array에 있는 각각의 item에 대해 function을 실행할 수 있게 해준다.
- function sayHello(item){
console.log("this is the turn of ", item);
}
위 두 코드가 하는 일은 같다.
두 번째 코드의 =>는 화살표 함수(Arrow function)라고 한다.
- 밀리초(1000분의 1초)를 주는 함수인 Date.now()를 이용해 랜덤으로 ID를 만들 수 있다.
- array에서 뭔가를 삭제한다는 것은 실제로는 지우고 싶은 item을 빼고 새 array를 만드는 것이다.
이때, filter 함수를 이용할 수 있다. → array의 item을 유지하고 싶으면 true를 리턴해야 한다.
<날씨와 위치> <= 다음에 다시 보기 !
const API_KEY = " *** ";
function onGeoOk(position){
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log("You live in ", lat, lon);
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
fetch(url).then(response => response.json()).then(data =>{
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
city.innerText = data.name;
weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
});
}
function onGeoError(){
alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
- user의 위치를 주는 함수인 navigator를 이용해 위치를 확인한 후, 해당 위치의 날씨를 API(https://openweathermap.org/api)를 이용해 얻어온다.
'JavaScript' 카테고리의 다른 글
자바스크립트의 타입 (0) | 2023.01.24 |
---|---|
노마드 코더 바닐라JS로 크롬 앱 만들기 후기 (11.21~12.04 챌린지 졸업) (0) | 2022.12.27 |
노마드 코더 바닐라JS로 크롬 앱 만들기 복습용 정리(3) (0) | 2022.12.01 |
노마드 코더 바닐라JS로 크롬 앱 만들기 복습용 정리(2) (0) | 2022.11.25 |
노마드 코더 바닐라JS로 크롬 앱 만들기 복습용 정리(1) (0) | 2022.11.24 |
댓글