CHAPTER 10. DOM 과이벤트처리, 입력검 증
문서객체모델 (DOM) DOM 은 HTML 문서의계층적인구조를트리 (tree) 로표현
DOM 과 BOM HTML 문서를객체로표현한것을 DOM 웹브라우저를객체로표현한것을 BOM(Browser Object Model)
HTML 요소찾기 동적인웹페이지를작성하려면원하는요소를찾아야한다. id 로찾기 태그이름으로찾기
id 로 HTML 요소찾기 <!DOCTYPE > <html> <head> function process() { var obj = document.getelementbyid("target"); alert(obj.value); </head> <body> <form name="myform"> <input type="text" id="target" name="text1"> <input type="submit" value=" 제출 " onclick="process()"> </form> </body> </html>
입력양식찾기 <!DOCTYPE > <html> <head> function process() { var obj = document.myform.text1; alert(obj.value); </head> <body> <form name="myform"> <input type="text" id="target" name="text1"> <input type="submit" value=" 제출 " onclick="process()"> </form> </body> </html>
태그이름으로 HTML 요소찾기 <!DOCTYPE > <html> <body> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> var list = document.getelementsbytagname('ul')[0]; var allitems = list.getelementsbytagname('li'); for (var i = 0, length = allitems.length; i < length; i++) { alert(allitems[i].firstchild.data); </body> </html>
DOM 트리순회
<!DOCTYPE html> <html> HTML 요소의내용변경 <head> <title></title> function get() { var val = document.getelementbyid("ex").innerhtml; alert(val); function set(v) { document.getelementbyid("ex").innerhtml = v; </head> <body> <div id="ex"> 여기가 div 로선언되었습니다.</div> <a href="#" onclick="get()">div 요소내용출력하기 </a><br /> <a href="#" onclick="set(' 변경되었습니다.')">div 요소내용변경하기 </a> </body> </html>
실행결과
<!DOCTYPE html> 요소의속성변경하기 <html> <body> <img id="image" src="pome.png" width="120" height="100"> function changeimage() { document.getelementbyid("image").src = "poodle.png"; <input type="button" onclick="changeimage()" value=" 눌러보세요 " /> </body> </html>
<!DOCTYPE html> <html> 요소의스타일변경하기 <body> <p id="p1">this is a paragraph.</p> function changestyle() { document.getelementbyid("p1").style.color = "red"; document.getelementbyid("p1").style.fontfamily = "Century Schoolbook"; document.getelementbyid("p1").style.fontstyle = "italic"; <input type="button" onclick="changestyle()" value=" 눌러보세요 " /> </body> </html>
새로운 HTML 요소생성 function addtext(t) { if (document.createtextnode) { var node = document.createtextnode(t); document.getelementbyid("target").appendchild(node); <div id="target" onclick="addtext(' 동적으로텍스트가추가됩니다.')" style="font: 20px bold;"> 여기를클릭하세요.</div>
HTML 요소삭제 <!DOCTYPE html> <html> <head> function removenode() { var parent = document.getelementbyid("target"); var child = document.getelementbyid("p1"); parent.removechild(child); </head> <body> <div id="target"> <p id="p1"> 첫번째단락 </p> <p id="p2"> 두번째단락 </p> </div> <button onclick="removenode()"> 누르세요!</button> </body> </html>
브라우저객체모델 브라우저객체모델 (BOM: Browser Object Model): 웹브라우저가가지고있는모든객체를의미 최상위객체는 window 이고그아래로 navigator, location, history, screen, document, frames 객체가있다.
새로운윈도우오픈예제 <!DOCTYPE html> <html> <head></head> <body> <form> <input type="button" value=" 구글창열기 " onclick="window.open('http://www.google.com', '_blank', 'width=300, height=300', true)"> </form> </body> </html>
settimeout()
예제 <!DOCTYPE html> <html> <head> function showalert() { settimeout(function () { alert("settimeout() 을사용하여표시됩니다."), 3000); </head> <body> <p> 버튼을누르면 3 초후에경고박스가화면에표시됩니다. </p> <button onclick="showalert()"> 눌러보세요 </button> </body> </html>
setinterval()
예제 <!DOCTYPE html> <html> <head> var id; function changecolor() { id = setinterval(flashtext, 500); function flashtext() { var elem = document.getelementbyid("target"); elem.style.color = (elem.style.color == "red")? "blue" : "red"; elem.style.backgroundcolor = (elem.style.backgroundcolor == "green")? "yellow" : "green"; function stoptextcolor() { clearinterval(id); </head>
예제 <body onload="changecolor();"> <div id="target"> <p>this is a Text.</p> </div> <button onclick="stoptextcolor();"> 중지 </button> </body> </html>
screen 객체
예제 function maxopen(url, winattributes) { var maxwindow = window.open(url, "", winattributes) maxwindow.moveto(0, 0); maxwindow.resizeto(screen.availwidth, screen.availheight) <a href="#" onclick="maxopen('http://www.google.com', 'resize=1, scrollbars=1, status=1'); return false"> 전체화면보기 </a>
location 객체
예제 function replace() { location.replace("http://www.google.com") <a href="#" onclick="replace()"> 이동하기 </a>
navigator 객체
예제 for (var key in navigator) { value = navigator[key]; document.write(key + ": " + value + "<br>");
이벤트처리
onclick 이벤트 <!DOCTYPE html> <html> <head> function changecolor(c) { document.getelementbyid("target").style.backgroundcolor = c; </head> <body id="target"> <form method="post"> <input type="radio" name="c1" value="v1" onclick="changecolor('lightblue')"> 파랑색 <input type="radio" name="c1" value="v2" onclick="changecolor('lightgreen')"> 녹색 </form> </body> </html>
onload 와 onunload 이벤트 <html> <head> function onloaddoc() { alert(" 문서가로드되었습니다."); document.body.style.backgroundcolor = "red"; </head> <body onload="onloaddoc();"> </body> </html>
onchange 이벤트 <!DOCTYPE html> <html> <head> function sub() { var x = document.getelementbyid("name"); x.value = x.value.tolowercase(); </head> <body> 영어단어 : <input type="text" id="name" onchange="sub()"> <p> 입력필드를벗어나면소문자로변경됩니다.</p> </body> </html>
<html> <head> function OnMouseIn(elem) onmouseover 이벤트 { elem.style.border = "2px solid red"; function OnMouseOut(elem) { elem.style.border = ""; </head> <body> <div style="background-color: yellow; width: 200px" onmouseover="onmousein (this)" onmouseout="onmouseout (this)"> 마우스를이요소위에이동하세요. </div> </body> </html>
onmousedown 이벤트 <html> <head> function OnButtonDown(button) { button.style.color = "#ff0000"; function OnButtonUp(button) { button.style.color = "#000000"; </head> <body> <button onmousedown="onbuttondown (this)" onmouseup="onbuttonup (this)"> 눌러보세요!</button> </body>
계산기예제 <html> <head> var expression=""; function add(character) { expression = expression + character; document.getelementbyid("display").value = expression; function compute() { document.getelementbyid("display").value = eval(expression); function cleardisplay() { expression = ""; document.getelementbyid("display").value = "0";
계산기예제 <body> <form> display <input id="display" value="0" size="30"> <br> <input type="button" value=" 7 " onclick="add('7')"> <input type="button" value=" 8 " onclick="add('8')"> <input type="button" value=" 9 " onclick="add('9')"> <input type="button" value=" / " onclick="add('/')"> <br> <input type="button" value=" 4 " onclick="add('4')"> <input type="button" value=" 5 " onclick="add('5')"> <input type="button" value=" 6 " onclick="add('6')"> <input type="button" value=" * " onclick="add('*')"> <br> <input type="button" value=" 1 " onclick="add('1')"> <input type="button" value=" 2 " onclick="add('2')"> <input type="button" value=" 3 " onclick="add('3')"> <input type="button" value=" - " onclick="add('-')"> <br> <input type="button" value=" 0 " onclick="add('0')"> <input type="button" value=" + " onclick="add('+')"> <br> <input type="button" value=" Clear " onclick="cleardisplay()"> <input type="button" value=" Enter </form> </body> </html> " name="enter" onclick="compute()">
웹브라우저실행 실행결과
폼의유효성검증 입력필드에서의잘못을검증하는작업 <h3> 회원가입 </h3> <form> 이름 : <input type='text' id='name' /><br /> 주소 : <input type='text' id='addr' /><br /> 생일 : <input type='date' id='birthday' /><br /> 아이디 (6-8 문자 ): <input type='text' id='username' /><br /> 이메일 : <input type='email' id='email' /><br /> 휴대폰 : <input type='tel' id='phone' /><br /> <input type='submit' value=' 확인 ' /><br /> </form>
공백검증 function checknotempty(field) { if (field.value.length == 0) { alert(" 필드가비어있네요!"); field.focus(); return false; return true; <form> 이름 : <input type='text' id='user' /> <input type='button' onclick="checknotempty(document.getelementbyid('user'))" value=' 확인 ' /> </form>
데이터길이검증 function checklength(elem, min, max) { var s = elem.value; if (s.length >= min && s.length <= max) { return true; else { alert(min + " 문자와 " + max + " 문자사이로입력해주세요!"); elem.focus(); return false; <form> 이름 (6-8 문자 ): <input type='text' id='name' /> <input type='button' onclick="checklength(document.getelementbyid('name'), 6, 8)" value=' 확인 ' /> </form>
정규식 정규식 (regular expression): 특정한규칙을가지고있는문자열들을표현하는수식이다 ( 예 ) ^[0-9]+abc$
숫자검증예제 function checknumeric(elem, msg) { var exp = /^[0-9]+$/; if (elem.value.match(exp)) { return true; else { alert(msg); elem.focus(); return false; <form> 전화번호 (- 없이입력 ): <input type='text' id='phone'/> <input type='button' onclick="checknumeric(document.getelementbyid('phone'), ' 숫자만입력하세요!')" value=' 확인 ' /> </form>