함수의 활용
예시) 주/야간모드 토글버튼 : this & self

<head>
<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 = 'white';
self.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color = 'blue';
i = i + 1;
}
}
}
</script>
</head>
<h1><a href="index.html">WEB</a></h1>
<input id="night_day" type="button" value="night" onclick="
nightDayHandler(this);
">
<input id="night_day" type="button" value="night" onclick="
nightDayHandler(this);
">
<head>안에 <input>에 적용 될 <script>코드를 작성한다.
작성한 script코드를 'function 함수명(){}'로 감싸준다.
<input>에 this를 준다. ex) 함수명(this);
<script>에 매개변수의 이름을 self로 정의한다. ex) function 함수명(self);
<script>의 value값을 self로 전부 적용한다. ex) self.value
Last updated
Was this helpful?