리팩토링 - 코드가 비효율적일때 가독성과 편리성을 위해 중복된 코드 등을 개선해주는 작업
<input
id="night_day2"
type="button"
value="night"
onclick="
if(document.querySelector('#night_day2').value === 'night'){
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#night_day2').value = 'day';
// true라고 될 때의 값을 입력
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#night_day2').value = 'night';
} //이것은 연산문을 false라고 판단하게 될 때의 값을 입력
" /> // 이런 버튼을 아래에 똑같이 복사하면 제 기능을 하지만 클릭했을 때
위의 버튼의 이름만 바뀌는 것을 확인할 수 있다
제 기능을 다 하고싶게 만들면 night_day라는 id를 따로 구분(night_day2)해줘야한다 그래서 이러한 불편함을 해결해보자
위의 스위치 코드는 사실은 자기 자신을 가르키는 코드입니다 온클릭 안에서 자기 자신만들 가리키고 있는데
document.querySelector('#night_day2')라는 벨류앞의 값들을 모두 this로 바꿔줍니다
그리고 id는 지워주자 잘 동작한다 신기하다?
코딩을 잘하는 방법 >> 중복을 끝까지 찾아가서 없애버리거나 더욱 간결하게 만들기
<input type="button"
value="night"
onclick="
const target =document.querySelector('body') //타겟은 바디 태그로 지정
if(this.value === 'night'){
target.style.backgroundColor = 'black'; // 중복되는 태그 네임을 모두 target으로 수정
target.style.color = 'white';
this.value = 'day';
// true라고 될 때의 값을 입력
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
} //이것은 연산문을 false라고 판단하게 될 때의 값을 입력
"
/>
그 밖의 비효율적인 코드 작성을 수정해보자
반복문 작성 > 배열과 반복문 다음 시간부터 알아보자
'디자인' 카테고리의 다른 글
그림판 만들기 js (0) | 2021.01.18 |
---|---|
클릭하면 나오는 modal 만들기 (0) | 2021.01.17 |
생코 ajax 2 (0) | 2021.01.14 |
생활코딩 자바스크립트 다시보기.. (0) | 2021.01.13 |
객체2 자바스크립트 (0) | 2021.01.12 |