본문 바로가기

JavaScript

자바스크립트 함수 기초



[ex1] this와 id로 함수호출
<head>
    <script>
        function a(obj){
        obj.value="ccc";             //this로 매개변수이용법
  }

  function b(){
        joo.value="jajaeju";                //아이디사용방식. id를 마치 객체처럼사용
        document.getElementById("joo").value="jajaeju";         
        // 그런데 id를 찾는방법중 대부분이 밑에 getElemtById를 쓴다.
        // 이유는 잘모르겠지만 웹표준인가?????      
  }
    </script>
</head>
<body>
    <input type="button" value="aaa" onclick="a(this)">
    <input type="button" value="jo" id="joo" onclick="b()">
</body>

 

[ex] className :  해당 태그의 class명을 바꿈  
      아래와 같이 해당 태그의 style과 class명을 바꿀수 있다. 
<html>
<head>
    <style type="text/css">
        .s1 {
            background-color: navy;
        }

        .s2 {
            background-color: yellow;
        }
    </style>
    <script>
        function m(a) {

          if (a.className == "s2") {
               a.className = "s1";                               
          } else {
               a.className = "s2";                              
          }

     }
</script>
</head>

<body>
    <input type="button" value="red" class="s1" id="b1" onclick="m(this)">
    <input type="button" value="green" class="s2" id="b2" onclick="m(this)">
</body>

</html>

[ex] 스크립트로 스타일 접근
<head>
    <style type="text/css">
        div {
            border: red 2px solid;
            width: 200px;
        }
    </style>
    <script>
        function m(a) {
            a.style.borderColor = "green";
         // style붙히고 border-color => borderColor(하이픈지우고 연결두번째첫글자 대문자!)

        }
    </script>
</head>
<body>
    <div onclick="m(this)">aaa</div>
</body>



'JavaScript' 카테고리의 다른 글

폼태그 및 접근법  (0) 2019.03.04
이벤트 처리  (0) 2019.03.04
태그 속성 접근  (0) 2019.03.04
this와 var의 차이점  (0) 2019.03.04
함수 선언방법  (0) 2019.03.04