현재 실행되고있는 문맥 : document.querySelector('#night_time') -> this
- 반복문과 배열
서로 연관된 데이터들을 배열에 담고, 반복문을 통해 배열에서 데이터를 꺼내오자
<script>
var coworkers = ['egoing', 'lee','daru','park'];
</script>
<h2>Coworkers</h2>
<ul>
<script>
var i =0;
while(i<coworkers.length){
document.write('<li><a href="http://a.com/'+coworkers[i]+'">'+coworkers[i]+'</a></li>');
i=i+1;
}
</script>
</ul>
- 반복의 조건 : 배열의 길이 가져오기 ( .length )
- 반복문 내 실행 내용 : ('<태그>''+배열[i]+''<태그>')
- 반복문과 배열 활용
( console 창에서 줄바꿈 : shift + enter )
Q : javascript get element by css selector multiple ?
A : Get all elements in the document with class="example": varx =document.querySelectorAll(".example");
//Console
var alist = document.querySelectAll('a');
var i =0;
while(alist.length){
console.log(alist[i]);
i = i+1;
}
//a 태그를 alist 배열에 저장, 반복문을 통해 모든 a 태그 들을 불러올 수 있다.
<input id="night_day" 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;
}
}
">
<script>
function nightDayHandler(self){
//function 임을 알려주고, 함수 이름
// 전달받은 파라미터 this를 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>
function nightDayHandler를 만들었다. !
<input id="night_day" type="button" value="night" onclick="
nightDayHandler(this)"
>
<input id="night_day" type="button" value="night" onclick="
nightDayHandler(this)"
>
//위의 길 었던 input 태그는 간결해지고! 유지 보수에도 편리할 것 같다는게 확 느껴진다.
var grad = {
'list' : {'egoing':10, 'park':20, 'kke':30},
'show' : function(){
for(var name in this.list){
//this : funtion을 소유하고 있는 객체를 가리키는 변수
console.log(name + " "+ this.list[name]);
}
}
} //객체 - 객체도, 함수도 객체의 멤버로
console.log(grad['list']['egoing']); // 객체안의 객체
//grad['show']();
grad.show(); //객체안의 함수