달력

3

« 2024/3 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
Pro Javascript를 전체적으로 한번 흩어 보고나서는, Javascript에 대한 이해도가 무척 높아졌다. 물론 당연히 알아야 할 것들을 그동안 모르는 채 잘 지내왔을 뿐이다.
내가 알던 쉬운 자바스크립트는 지금의 것과는 너무도 많이 달랐다. 아니 자바스크립트의 가능성과 기능에 대해서 너무 간과해 왔는지도 모른다.

HTML의 DOM 구조는 개발자로 하여금 문서의 구조을 쉽게 이해할 수 있도록 도와주고, 이는 CSS와
Javascript를 통해서 쉽게 제어할 수 있어 매우 유용하다.

<html>
<head>
<title>Introduction to the DOM</title>
<script>
    // We can't manipulate the DOM until the document
    // is fully loaded
    window.onload = function(){
    // Find all the <li> elements, to attach the event handlers to them
    var li = document.getElementsByTagName("li");
    for ( var i = 0; i < li.length; i++ ) {
        // Attach a mouseover event handler to the <li> element,
        // which changes the <li>s background to blue.
        li[i].onmouseover = function() {
            this.style.backgroundColor = 'blue';
        };

        // Attach a mouseout event handler to the <li> element
        // which changes the <li>s background back to its default white
        li[i].onmouseout = function() {
            this.style.backgroundColor = 'white';
        };
    }
};
</script>
</head>
<body>
<h1>Introduction to the DOM</h1>
<p class="test">There are a number of reasons why the
DOM is awesome, here are some:</p>
<ul>
    <li id="everywhere">It can be found everywhere.</li>
    <li class="test">It's easy to use.</li>
    <li class="test">It can help you to find what you want, really quickly.</li>
</ul>
</body>
</html>

위의 코드는 "Pro Javascript"에 나오는 예제인데, HTML은 XML의 구조를 가지고 있지만, 가장 단순한 형태중에 하나로 문서를 구성하는 Object를 정의하고 있다. 이러한 구조는 "태그(Tag)"라는 형태로 정의되어지는데, 위 예제는 태그에 Event의 handler를 할당하는 코드이다.

코드에 대한 설명을 덧 붙이자면,
1. var li = document.getElementsByTagName("li");
    - 위 코드를 통해서 HTML 문서에 정의된 "li" 태그들의 리스트를 가져와서 var li에 저장한다.
    - document.getElementsByTagName 메소드는 태그 이름을 이용하여 Element를 가져오는
      함수이다.

2. li[i].onmouseover = function() {this.style.backgroundColor = 'blue'; );
   - 위 코드를 정의하기 전에, "li.length"를 통해서 리스트의 갯수를 알수 있고 이를 For 루프 문의
     통해서 반복을 시킨다.
   - 이는 동일한 이벤트를 "li"태그로 정의된 Object에 할당하기 위새서이다.
   - li[i].onmouserover 이벤트 메소드는 위와 같이 새로 정의된 메소드를 통해서 마우스가 "li"태그
     위에서 움직일 때 태그의 배경색을 "blue"로 바꾸어 준다.

3. li[i].onmouseout = function() {this.style.backgroundColor = 'white'; };
    - 이 코드는 "li" 태그의 onmouseout event 메소드를 정의하는 코드로, 마우스가 태그를 벗어날때
      태그의 배경색을 "white"로 바뀌게 만들어 준다.

위의 코드를 이해할 수 있으면, jQuery에서 얼마나 직관적으로 같은 코드를 간략하고 단순한 형태로 사용할 수 있는지 알게된다면, 깊은 인상을 받을 것이다.
:
Posted by 행복상자