강의/Do it!
[Do it! 자바스크립트 기본] 08. 웹 문서를 다루는 방법, 문서 객체 모델(DOM) - 선택한 이미지 표시하기 (P243)
millfeel1298
2021. 3. 10. 12:24
피드백
- 프로그램 작성 순서를 구체적으로 계획을 짜고 코드를 짜도록 하자.
- 함수는 재활용을 하기 위해서 분리 작업을 하자.
- 유동성 있는 코드를 사용하자. (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 이벤트 함수를 연결할 때, 괄호를 붙이지 않는다.
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
[참고]