addEventListener 로 이벤트 붙이기

jb kim·2021년 8월 21일
0

심리사이트

목록 보기
6/16
post-thumbnail
function goNext(qIdx) {
  var q = document.querySelector('.qBox');
  q.textContent = qnaList[qIdx].q;
  for (let i in qnaList[qIdx].a) {
    addAnswer(qnaList[qIdx].a[i].answer, qIdx)
  }
}

function addAnswer(answerText, qIdx) {
  var a = document.querySelector('.answerBox');
  var answer = document.createElement('button');
  a.appendChild(answer);
  answer.textContent = answerText;
  //answer.addEventListener('click', e => console.log(e));
  //answer.addEventListener('click', e => e.target.style.display = 'none');
  answer.addEventListener('click', (e) => {
    //console.log(e.target.parentNode);
    e.target.parentNode.querySelectorAll('*').forEach(n => n.remove());
    goNext(++qIdx);
  });
}

답변 버튼중 하나를 누를때 마다 다음 질문이 나타난다.




자바스크립트 반복문 정리

  • for 문: 고전적인 for문

for (let i = 0; i < 10; i++){
console.log(i); // 0~9까지 출력
}

  • for in 문: 객체의 키값 열거

const obj = {
name: '길동',
job: '프로그래머'
}

for (let key in obj){
console.log( key, obj[key]);
}

  • for of 문: 이터러블 순회 전용

const arr = [10, 20, 30];
for (const item of arr){
console.log(item); // 10, 20, 30 출력
}
(참고) 이터러블에는 String, Array, Map, Set, DOM컬렉션(HTMLColletion, NodeList) 등이 있다.

  • forEach(): 배열 순회 전용 메서드

콜백함수의 매개변수로 value에 요소값, index에 인덱스, array에 원본 배열이 들어온다.

[10, 20, 30].forEach((value, index, array)=>{
console.log(index, value); // 0 10, 1 20, 2 30 출력
})

출처: https://curryyou.tistory.com/202 [카레유]

profile
픽서

0개의 댓글