seoyoung.dev

javascript 기초 문법 본문

WEB/Javascript

javascript 기초 문법

seo-0 2019. 9. 17. 15:24
- 태그 제어 
<input type="button" value="night" onclick="
  document.querySelector('body').style.backgroundColor='black';
  document.querySelector('body').style.color='white'; 
">
<input type="button" value="day" onclick="
  document.querySelector('body').style.backgroundColor='white';
  document.querySelector('body').style.color='black';
">

: 버튼눌렀을 때, body 태그 스타일의 배경: black, 글자color: white

Document.querySelector()는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환합니다. 일치하는 요소가 없으면 null을 반환합니다. )

- 조건문 활용

-> night, day 두 개의 버튼을 하나의 버튼으로 대신하여, night일 때는, 버튼: day && day일 때는 버튼: night

	  <input id="night_time"type="button" value="night" onclick="
      
      if(document.querySelector('#night_time').value === 'night'){
      document.querySelector('body').style.backgroundColor='black';
      document.querySelector('body').style.color='white';
      document.querySelector('#night_time').value = 'day';}
      
       else{
        document.querySelector('body').style.backgroundColor='white';
        document.querySelector('body').style.color='black';
        document.querySelector('#night_time').value ='night';
      }" >
- 리팩토링 ( 중복 제거 )
    <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';
     }" >

현재 실행되고있는 문맥 : 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":   var x = 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;
        }
      }
      ">

--> 결과 화면

...더보기
< day >
< night >

... 암만 봐도 비효율적이니까 함수를 쓰자.

- 함수 
<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 태그는 간결해지고! 유지 보수에도 편리할 것 같다는게 확 느껴진다. 

- 함수 [ 파라미터 / 인자 / 리턴 ]
<h2> parameter & argument </h2>
    <script>
      function onePlusOne(){
          document.write(1+1+'<br>');
      }
      function sum(left, right){
        document.write(left +right+'<br>');
      }
      function sumColorRed(left, right){
        document.write('<div style="color:red">'+(left+right)+'</div><br>');
      }
        onePlusOne();
        sum(2,3); // 5
        sumColorRed(2,3); // 5
    </script>

<h2>Return</h2>
   <script>
      function sum2(left, right){
       return left+right;
      }
      document.write(sum2(2,3)+'<br>');
      document.write('<div style="color:red">'+sum2(3,4)+'</div>');
      document.write('<div style="font-size:3rem;">'+sum2(3,4)+'</div>');
  </script>

- 결과 페이지


* 객체
<h2>Create</h2>
    <script>
          var coworkers = {
            "programmer": "egoing",
            "designer": "leezche"
          }; //객체 생성

          document.write("programmer :" + coworkers.programmer+"<br>");
          document.write("designer :" + coworkers.designer+"<br>");
          coworkers.bookkeeper = "duru"; //객체 생성2
          document.write("bookkeeper :" + coworkers.bookkeeper+"<br>");
          coworkers["data scientist"]="taeho";// 객체 생성3
          document.write("data scientist :" + coworkers["data scientist"]);
    </script>

- javacript 의 객체 에 객체도, 함수도 담을 수 있다. 

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(); //객체안의 함수