검색 history 추가

YEONGHUN KO·2021년 11월 17일
0

PYTHON - SCRAPPER

목록 보기
15/17
post-thumbnail

검색 history 기능 추가.

참 많이 돌아왔다 이 기능은 사실 스크래퍼 챌린지 하다가 다른 우수 졸업자들의 작품을 보고 영감을 받아서 만들려고 했던건데 자바스크립트로 구현되어있어서 자바스크립트 공부하고 다시 만들자고 했던건데 드디어 다 구현했다! 그럼 우선 history가 위치할 틀을 html, form 태그 밑에 추가해주자

<div class="history">
    <ul class="list">
        
    </ul>
</div>

history.js 추가

x 버튼을 history 옆에 추가하여 x를 눌렀을때 history가 없어지도록 했고 이전 history와 같은 history를 검색했을때는 history가 추가되지 않도록 했다.\
로직순서는 아래와 같다.(todo list 만들때 사용되던 코드랑 거의 같다)

1. 엔터를 눌렀을때 input.value를 가져온다.

2. 가져온 value를 display 함수에 pass 하고 그 함수에서 li, button 을 만든다음 value와 합쳐서 history 클래스안에 추가한다.

3. history를 array안에 push 하고 Localstorage에 저장한다.

우선 DOM을 변수를 설정하고 init 함수를 만들자.

const job_form = document.querySelector(".job_form"),
  job_input = job_form.querySelector("input"),
  history = document.querySelector(".list");
const historyList = "history";
let inputHistory = [];


function init() {
  job_form.addEventListener("submit",handleHistory);
  loadList();
}

init();

그리고 엔터를 눌렀을때 handleHistory가 작동되야한다.


function handleHistory(event) {
  event.preventDefault();
  const currentValue = job_input.value;
  var i;
  for (i = 0; i < inputHistory.length; i++){
    var bool = inputHistory[i].text.includes(currentValue); 
    //include 함수는 말그대로 텍스트가 포함되어있는지를 보는 함수이다. boolean 형태다.
    if (bool === true) {
      job_input.value = "";
      console.log(inputHistory[i].text)
      console.log("same")
      return
    }
    
  }
  displayHistory(currentValue);
  job_input.value = "";
}

display 하기

function displayHistory(text){
  const li = document.createElement("div");
  const delBtn = document.createElement("button");
  const anchor = document.createElement("a");
  const newId = inputHistory.length + 1;
  anchor.href = "/detail?job=" + text;
  anchor.innerHTML = text;
  delBtn.innerHTML = "❌";
  delBtn.addEventListener("click",delHistory);
  anchor.addEventListener("click", ()=> {
    console.log("anchor click")
    loading.style.visibility='visible';
  })
  li.appendChild(anchor);
  li.appendChild(delBtn);
  li.id = newId;
  history.appendChild(li);
  const historyObj = {
    text:text,
    id:newId
  };
  inputHistory.push(historyObj);
  saveHisotry();
  console.log("displayHistory")
}

delete 버튼함수 만들고 Localstorage에 저장하기.


function saveHisotry() {
  localStorage.setItem(historyList,JSON.stringify(inputHistory));
}

function delHistory(event) {
  const btn = event.target;
  const li = btn.parentNode;
  history.removeChild(li);
  const cleanHistory = inputHistory.filter(function(his){
    console.log(li.id, his.id);
    return his.id !== parseInt(li.id);
  })
  inputHistory = cleanHistory;
  saveHisotry();

}

로딩함수 만들기


function loadList() {
  const loadedHistory = localStorage.getItem(historyList);
  if (loadedHistory !== null){
    const parsedHistory = JSON.parse(loadedHistory);
    parsedHistory.forEach(function(eachHistory) {
      displayHistory(eachHistory.text);
    });
  }
}

그런데 역시나 문제가 생겼다(문제가 안생기면 코딩이 아니지 ㅋㅋㅋ) history가 나타난다. 신기하다! 엔터를 누르고 나서 다음화면으로 넘어가지가 않는다...도대체 뭐가 문제란 말인가.. 명령프롬프트를 보니깐 /detail?job= 처럼 job 뒤에 아무것도 입력되어있지 않다. submit이 안된다는 얘기다.

그래서 javascript submit 을 검색하니 form.submit() 이라고 입력하면 submit이라고 잘 작동된다는 것이다. 그럼 handleHistory 안에 입력해야하는 구먼.


function handleHistory(event) {
  event.preventDefault();
  job_form.submit();
  .
  .
  .
}

잘 작동된다! 그럼 css를 추가해주자

css 추가


.history .list {
  display: grid;
  margin: 2vmin 20vmin;
  grid-template-columns: repeat(8,19vmin);
  grid-template-rows: repeat(2,4vmin);
  grid-auto-rows: 2vmin;
  grid-row-gap: 6vmin;
}

.history .list div {
	display: flex;

}

.history a {
  text-decoration: none;
  color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  background-position: center;
  background-color: rgba(235, 205, 15,1);
  height: 7vmin;
  width: 13vmin;
  border-radius: 6vmin;
  background-size: contain;
  font-size: 3vmin;
}

.history .list button {
	background: transparent;
	border: none;
	font-size: 10px;
  padding: 0;
}

끝! 그럼 로딩화면을 추가해보는건 다음글에서 설명하겠다.

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글