티스토리 뷰

피드백

  1. 프로그램 작성 순서를 구체적으로 계획을 짜고 코드를 짜도록 하자.
  2. 함수는 재활용을 하기 위해서 분리 작업을 하자.
  3. 유동성 있는 코드를 사용하자. (this, elem의 속성)

코드 수정

수정 전

const smallImg = document.querySelectorAll('.small');

smallImg.forEach(function (elem) {
  elem.onclick = function() {
    const elemSrc = elem.getAttribute('src');
    const bigChange = elem.parentElement.previousElementSibling;

    bigChange.setAttribute('src', elemSrc);
  }
});

 

1차. 함수 재활용을 위한 함수 분리

const smallImg = document.querySelectorAll('.small');

smallImg.forEach(function(elem) {
  elem.onclick = showImg;
});

function showImg(){
  const elemSrc = elem.getAttribute('src');
  const bigChange = elem.parentElement.previousElementSibling;

  bigChange.setAttribute('src', elemSrc);
}

[주의] onclick 이벤트 함수를 연결할 때, 괄호를 붙이지 않는다.

*on<event> handler

 

 

2차. event.target을 사용

const smallImg = document.querySelectorAll('.small');

smallImg.forEach(function(elem) {
  elem.onclick = showImg;
});

function showImg(event){
  const target = event.target;
  const elemSrc = target.getAttribute('src');
  const bigChange = target.parentElement.previousElementSibling;

  bigChange.setAttribute('src', elemSrc);
}

틀린 방법은 아니지만 "this"를 활용하면 코드를 줄일 수 있다.

 

 

2-1차. event.target을 this로 변경

const smallImg = document.querySelectorAll('.small');

smallImg.forEach(function(elem) {
  elem.onclick = showImg;
});

function showImg(){
  const elemSrc = this.getAttribute('src');
  const bigChange = this.parentElement.previousElementSibling;

  bigChange.setAttribute('src', elemSrc);
}

 

 

3차. Element의 속성 활용 (완성)

const smallImg = document.querySelectorAll('.small');

smallImg.forEach(function(elem) {
  elem.onclick = showImg;
});

function showImg(){
  const elemsrc = this.src;
  const bigChange = this.parentElement.previousElementSibling;

  bigChange.setAttribute('src', elemsrc);
}
P246
예약어 this는 click 이벤트가 발생한 요소, 즉 누른 작은 이미지를 가리킵니다.
그렇다면 this.src는 작은 이미지의 파일 경로를 가리키겠죠?

네??? 애초에 저 Element가 src속성을 가지고 있는지 어떻게 알아요?

아 ~ 다 가지고 있나?

this.src // 경로 반환
this.class // undefined 반환

다 안가지고 있잖아요!!!!


Q. Element가 내가 원하는 속성을 가지고 있는지 어떻게 알 수 있을까?

console.dir(this);

console.dir 속성을 가지고 확인하도록 하자.


[공부 좌표]

Do It! 자바스크립트 기본편 P243 ~ 246

console.dir()

 

[참고]

on<event> handler

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함