본문 바로가기

sparta/걷기반&달리기반

[달리기반] ToDoList_01

css와 js를 연결하여 만들기로 했다!

1. 할 일을 추가 할 수 있는 투두 리스트를 만듭니다.
2. HTML로 기본구조를 만듭니다.
3. 자바스크립트로 할 일 추가 기능을 구현합니다.
4. (선택) CSS로 간단한 스타일을 적용합니다.
5. (선택) 할 일 항목의 완료 표시, 삭제 기능을 구현합니다.

  • HTML, CSS, JS

사용자가 웹 사이트를 보고 상호작용 할 수 있도록 웹 애플리케이션을 만드는 게 중요하다.

HTML, CSS는 주로 구조와 스타일을 담당하지만 상호작용을 가능하게 하는 기능은 자바스크립트에서 주로 담당한다.


  • DOM

브라우저 렌더링, HTML문서의 조작을 위한 인터페이스 역할을 한다.

브라우저는 HTML을 읽어 DOM 트리구조를 만들고 자바스크립트는 DOM을 통해 웹 페이지의 내용을 변경, 추가, 삭제 할 수 있다. 즉, 자바스크립트가 웹 페이지의 구조와 내용을 조작할 수 있는 인터페이스이며 브라우저가 페이지를 렌더링하는 데 필요한 기본 구조를 제공한다.


  • 실습 전 기억해야 할 세가지 

1. 요소검색 -> querySelector

2. 상호작용 만들기 ->addEventListener

3. CSS변경 ->style속성(property)

<p id="myParagraph">버튼을 클릭하면 글자색이 바뀝니다.</p>
<button id="colorButton">글자색 변경</button>

<script>
  // 1. 요소 검색
  const paragraph = document.querySelector("#myParagraph");
  const button = document.querySelector("#colorButton");

  // 2. 상호작용 만들기(이벤트 등록)
  button.addEventListener("click", () => {
    // 3. CSS 변경
    paragraph.style.color = "violet";
  });
</script>

1. css와 자바스크립트를 연결해주기, 페이지명 짖기

    <title>to do list</title>
    <link rel="stylesheet" href="style.css" />
    <script src="./app.js"></script>

 

 

2. 구조 만들기

<div class="title">
        <h3>투두 리스트</h3>
    </div>
    <div class="box" type="box">
        <form>
            <input type="text" placeholder="오늘 해야 할 일!" />
            <button type="button" class="btn btn-outline-primary">추가</button>
        </form>
        <ul></ul>
    </div>

 

 

3. 자바스크립트에서 기능 구현하기

    1) 어떤 text를 입력했는지 가져오기

    2) list 아이템에 추가

const form = document.querySelector('form');
const input = document.querySelector('input');
const ul = document.querySelector('ul');

 

 

4. 아이템을 추가하면 리스트에 넣고 하면에 보이는 기능 구현하기

1) text가 비어있으면 추가할 수 없도록하기

2) 추가하면 추가완료 알림뜨기

3) 엔터를 치면 새로고침이 안되게 하기

4) 추가된 리스트에 삭제버튼과 완료버튼 뜨게 하기 

// 데이터 저장.
let todos=[];
const save=()=>{
    localStorage.setItem('todos', JSON.stringify(todos));
};
// 삭제버튼누르면 데이터도 삭제되게.
const delItem=(event)=>{
    // 이벤트 리스너 연결확인하기.
    // console.log('삭제!')
    // 클릭하고 있는 li전체 요소 삭제.
    // console.log(event.target.parentElement);
    const target = event.target.parentElement;
    todos=todos.filter((todo)=> {
        console.log(todo.id, target.id)
    })
    target.remove();
}
const addItem=(todo)=>{
    if (todo.text !== '') {
        const li = document.createElement('li');
        const button=document.createElement('button');
        const span=document.createElement('span');


// 추가하면 자식요소로 삭제버튼과 span태그가 뜸.
        span.innerText = todo.text;
        button.innerText='삭제'
        button.addEventListener('click',delItem);
        li.appendChild(span);
        li.appendChild(button);
        ul.appendChild(li);
        li.id=todo.id;
        alert("추가완료!");
        
    };
};
const handler=(event)=>{
    event.preventDefault();

    const todo={
        id: Date.now(),
        text: input.value
    };
    todos.push(todo);
    addItem(todo);
    save();
     // 엔터를 치면 새로고침안되게.
    input.value='';
};
// 동작
form.addEventListener('submit', handler);

완료된 일정 이벤트는 아직 안했...

 

 

 

 

 

아니 근데 왜 콘솔창에서는

데이터 입력값이 안뜨는거지1?!?!!??!

애플리케이션의 로털 스토리지에는

데이터가 잘 저장이 되어있는데!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 

 

 

 

 

삭제하면 로컬에서 삭제가 되는 걸 볼 수 있다. 하지만 콘솔창에 떠야 할 데이터가 안뜬다..?


전체코드



const form = document.querySelector('form');
// 어떤 text를 입력했는지 가져오기
const input = document.querySelector('input');
// list아이템에 추가
const ul = document.querySelector('ul');



// 데이터 저장.
let todos=[];
const save=()=>{
    localStorage.setItem('todos', JSON.stringify(todos));
};






// 삭제버튼누르면 데이터도 삭제되게.
const delItem=(event)=>{
    // 이벤트 리스너 연결확인하기.
    // console.log('삭제!')
    // 클릭하고 있는 li전체 요소 삭제.
    // console.log(event.target.parentElement);
    const target = event.target.parentElement;
    // 타입은 다르지만 내용물만 같으면 지워질 수 있게.
    todos=todos.filter((todo)=>todo.id!=target.id);
    save();
    
    target.remove();
};

//저장되는기능 추가
// 검사기능에서 application항목의 local storage에서 확인 가능.

const addItem=(todo)=>{
    if (todo.text !== '') {
        const li = document.createElement('li');
        const button=document.createElement('button');
        const span=document.createElement('span');


// 추가하면 자식요소로 삭제버튼과 span태그가 뜸.
        span.innerText = todo.text;
        button.innerText='삭제'
        button.addEventListener('click',delItem);
        li.appendChild(span);
        li.appendChild(button);
        ul.appendChild(li);
        li.id=todo.id;
        alert("추가완료!");
        
    };
};
const handler=(event)=>{
    event.preventDefault();

    const todo={
        id: Date.now(),
        text: input.value
    };
    todos.push(todo);
    addItem(todo);
    save();
     // 엔터를 치면 새로고침안되게.
    input.value='';
};

const init=()=>{
    const  userTodos=JSON.parse(localStorage.getItem('todos'));
    console.log(userTodos);
}
// 동작
form.addEventListener('submit', handler);

// 데이터 저장이 되는지 확인하기.
// hello라는 키로 저장한 값 worldrk 출력되는 걸 알 수 있음.
// localStorage.setItem('hello','world');
// const myDate =localStorage.getItem('hello');
// console.log(myDate);

    // console.log(input.value);
    // 작성자가 작성한 text넣기 변수명은 그냥 li로 지정함.
    // const li=document.createElement('li');

    // 작성한 text인 값을 가져오기
    // li.innerText=input.value;

    // 화면상에 출력이 되려면 문서에 구성되는 요소로 가져와야 함
    // ul.appendChild(li);

    // 입력하면 입력창 초기화하기.
    // input.value='';

 

 

연휴 때 너무 쉬었더니 몸이랑 정신이 괴로웠다 

내일 다시 끄적여봐야지