-
JavaScript 까먹은 거 다시 기록 (생활코딩 WEB2)프로그래밍 언어/JavaScript 2021. 9. 6. 23:30
1. 리팩토링
<input id="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if(document.querySelector('#night_day').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';
}
">2. 함수의 활용
<script>
function nightDayHandler(self){
var target = document.querySelector('body');
if(self.value === 'night'){
target.style.backgroundColor='black';
target.style.color='white';
self.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';
self.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color = 'blue';
i = i + 1;
}
}
</script><input id="night_day" type="button" value="night" onclick="nightDayHandler(this)">
3. 객체 활용
<script>
var Link = {
setColor:function(color){
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color = color;
i = i + 1;
}
}
}
var Body = {
setColor:function(color){
document.querySelector('body').style.color = color;
},
setBackgroundColor:function(color){
document.querySelector('body').style.backgroundColor = color;
}
}
function nightDayHandler(self){
var target = document.querySelector('body');
if(self.value === 'night'){
Body.setBackgroundColor('black');
Body.setColor('white');
self.value = 'day';
Link.setColor('powderblue');
} else {
Body.setBackgroundColor('white');
Body.setColor('black');
self.value = 'night';
Link.setColor('blue');
}
}
</script>4. jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
var Link = {
setColor:function(color){
$('a').css('color',color);
}
}
var Body = {
setColor:function(color){
$('body').css('color', color);
},
setBackgroundColor:function(color){
$('body').css('backgroundColor', color);
}
}'프로그래밍 언어 > JavaScript' 카테고리의 다른 글
Ajax (생활코딩 WEB2 - JavaScript) (0) 2021.09.07 Javascript 2일차 (생활코딩 WEB2) (0) 2021.09.03 JavaScript 1일차 (생활코딩 WEB2) (0) 2021.09.01