자바스크립트와 jQuery 비교
예제. 탭을 클릭했을 때 포커스를 변경하는 예제
JavaScript
<html> <head> <script type="text/javascript"> function addEvent(target, eventType,eventHandler, useCapture) { if (target.addEventListener) { // W3C DOM target.addEventListener(eventType,eventHandler,useCapture?useCapture:false); } else if (target.attachEvent) { // IE DOM var r = target.attachEvent("on"+eventType, eventHandler); } } function clickHandler(event) { var nav = document.getElementById('navigation'); for(var i = 0; i < nav.childNodes.length; i++) { var child = nav.childNodes[i]; if(child.nodeType==3) continue; child.className = ''; } event.target.className = 'selected'; } addEvent(window, 'load', function(eventObj) { var nav = document.getElementById('navigation'); for(var i = 0; i < nav.childNodes.length; i++) { var child = nav.childNodes[i]; if(child.nodeType==3) continue; addEvent(child, 'click', clickHandler); } }) </script> <style type="text/css"> #navigation li { list-style:none; float:left; padding:5px; } #navigation { cursor:pointer; } #navigation .selected { background-color:red; color:white; } </style> </head> <body> <ul id="navigation"> <li>HTML</li> <li>CSS</li> <li>javascript</li> <li class="selected">jQuery</li> <li>PHP</li> <li>mysql</li> </ul> </body> </html>
jQuery
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $('#navigation li').live('click', function() { $('#navigation li').removeClass('selected'); $(this).addClass('selected'); }) </script> <style type="text/css"> #navigation li { list-style:none; float:left; padding:5px; } #navigation { cursor:pointer; } #navigation .selected { background-color:red; color:white; } </style> </head> <body> <ul id="navigation"> <li>HTML</li> <li>CSS</li> <li>javascript</li> <li class="selected">jQuery</li> <li>PHP</li> <li>mysql</li> </ul> </body> </html>