티스토리 뷰
강의/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
[참고]
'강의 > Do it!' 카테고리의 다른 글
[Do it! 자바스크립트 기본] 06. 여러 자료를 한꺼번에 담는 객체 - 기념일 계산 프로그램 만들기 (P180) (0) | 2021.03.17 |
---|---|
[Do it! 자바스크립트 기본] 08. 웹 문서를 다루는 방법, 문서 객체 모델(DOM) - 상세 설명 보기/닫기 (P257) (0) | 2021.03.10 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- constructor
- __proto__
- prototype 프로퍼티
- 부등 연산자
- offsetHeight
- 프로퍼티
- 점 표기법
- [[Prototype]]
- 동치 연산자
- clinetTop
- clientHeight
- offsetTop
- scrollHeight
- scrollTop
- 일치 연산자
- 대괄포 표기법
- @font-face
- property
- 링크막기 #a링크막기
- outerHeight
- 객체의 프로퍼티
- innerHeight
- 동등 연산자
- javascript class
- 불일치 연산자
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함