일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
- 스프링
- SQL
- 브루트포스
- 컴퓨터 네트워크
- BFS
- AWS
- 재귀
- 트리
- 분할 정복
- 순열
- 그리드 알고리즘
- 도커
- 이분탐색
- 그래프
- 자료구조
- 다이나믹프로그래밍
- 그리드
- Spring
- GIT
- HTTP
- github action
- 역방향 반복자
- 분할정복
- 다이나믹 프로그래밍
- 백준
- 알고리즘
- CI/CD
- TCP
- 자바
- dfs
- Today
- Total
코딩성장스토리
javascript 두번째 도전기 본문
리팩토링 중복의 제거
똑같은 코드를 여러개 적어야만 할때 이름을 다르게 해야하므로 id나 class를 꾸준히 바꿔줘야한다 이걸 방지하기 위해 this가 존재한다.
<input id="nightday" type="button" value="night" onclick="
if(document.querySelector('#nightday').value==='night'){
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
document.querySelector('#nightday').value='day';
}else{
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
document.querySelector('#nightday').value='night';
}
">
아래는 this를 이용해서 쓴코드
<input type="button" value="night" onclick="
if(this.value==='night'){
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
this.value='day';
}else{
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
this.value='night';
}
">
그리고 여기서document.querySelector('body') 이 문구가 중복되는 것이 보인다.
이 중복을 없애기 위해서 변수var을 이용하면 간결해진다
예를 들어
<input type="button" value="night" onclick="
var target =document.querySelector('body');
if(this.value==='night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value='day';
}else{
target.style.backgroundColor='white';
target.style.color='black';
this.value='night';
}
">
배열과 반복문
배별 만드는법
<script>
var 변수이름=[, , , , ,];
</script>
이렇게 반복문과 배열을 이용하면
예시로
<input type="button" value="night" onclick="
var target =document.querySelector('body');
if(this.value==='night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value='day';
var alist= document.querySelectorAll('a');
var i=0;
while(i<alist.length){
alist[i].style.color='powderblue';
i=i+1;
}
}else{
target.style.backgroundColor='white';
target.style.color='black';
this.value='night';
var alist= document.querySelectorAll('a');
var i=0;
while(i<alist.length){
alist[i].style.color='blue';
i=i+1;
}
}
">
이런 응용이 가능하다.
'프론트 엔드 > javascript' 카테고리의 다른 글
javascript 세번째 도전 (0) | 2021.09.18 |
---|---|
javascript 도전기 (0) | 2021.09.18 |