Pro Javascript Techniques(4): Using the DOM and Events Tip & Tips/JavaScript2009. 3. 5. 23:27
내가 알던 쉬운 자바스크립트는 지금의 것과는 너무도 많이 달랐다. 아니 자바스크립트의 가능성과 기능에 대해서 너무 간과해 왔는지도 모른다.
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에서 얼마나 직관적으로 같은 코드를 간략하고 단순한 형태로 사용할 수 있는지 알게된다면, 깊은 인상을 받을 것이다.
'Tip & Tips > JavaScript' 카테고리의 다른 글
ExtJS의 그리드 기능 간단 분석 (0) | 2009.04.11 |
---|---|
Pro Javascript Techniques(3): Anonymous Functions (0) | 2009.02.17 |
Pro Javascript Techniques(2): Javascript Variable Scope (0) | 2009.02.08 |
Pro Javascript Techniques(1): Javascript DataType 체크 (0) | 2009.02.06 |