※ 내장 객체 서열
window : 창의 위치, 툴바 구성 등
|
document : 윈도우창에 웹 페이지 뿌리기
|
form, image
|
button, text, textarea, radio.... (value 로 접근)
< form > - get, post
<form name = "f">
<input type = "text" name = "t1">
</form>
// 이름이 t1인 입력 양식의 값 -- f.t1.value
form: 사용자가 입력한 데이터를 서버 페이지에 제출
=> 서버 페이지는 전달한 값들을 받아서 처리
<form action="서버 페이지 경로" method="전송방식(get/post)"></form>
- get (Servlet에서 doGet 호출) : 링크 이동 / url 쳐서 들어가는 것
: 데이터를 url 뒤에 붙여서 보냄. 보안 취약.
: url 길이의 제약이 있어 데이터 크기 제약됨.
: 한글이 더 많이 깨짐.
- post (Servlet에서 doPost 호출)
: 패킷에 데이터를 담아서 전송. => url 노출 되지 않음
: = 데이터 크기 제약 없음.
: 한글 덜 깨짐
get 방식과 post 방식을 합쳐서 구현할 때도 있음.......
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function a(){
let html = ""; // 공백 초기화
// 문자열 연결
// alert에서 줄바꿈 => "\n"
html += "id: " + f.id.value + "\n";
html += "pwd: " + f.pwd.value + "\n";
html += "phone: " + f.phone.value + "\n";
alert(html);
// f.ch는 사이즈가 4인 배열.
for(i=0; i<f.ch.length;i++){
if(f.ch[i].checked){ // 체크박스에서 값을 선택하면 alert
alert(f.ch[i].value); // 하나씩 각각 alert
}
}
// 라디오 버튼은 하나만 체크함.
alert(f.ra.value);
// select 박스도 value로 선택한 항목의 value값 읽음.
alert(f.sel.value);
// textarea
alert(f.hello.value);
// hidden
alert(f.h.value);
}
</script>
</head>
<body>
<h3>폼 양식</h3>
<form name = "f" action="/webApp1/MyServlet" method="post">
id:<input type="text" name="id"><br/>
pwd:<input type="password" name="pwd"><br/>
phone:<input type="number" name="phone"><br/>
<!-- 체크하면 true, 아니면 false -->
체크박스:<input type="checkbox" name="ch" value="1" checked>오렌지
<input type="checkbox" name="ch" value="2">키위
<input type="checkbox" name="ch" value="3">사과
<input type="checkbox" name="ch" value="4">배<br/>
라디오버튼:<input type="radio" name="ra" value="f" checked>여성복
<input type="radio" name="ra" value="m">남성복
<input type="radio" name="ra" value="c">아동복<br/>
콤보박스:
<select name="sel">
<option value="a">1학년</option>
<option value="b">2학년</option>
<option value="c">3학년</option>
<option value="d">4학년</option>
</select><br/>
여러줄입력:<textarea name="hello" rows="5" cols="40">가입인사를 적어주세요.</textarea><br/>
<!-- hidden: 화면에는 안보이지만 value값을 서버로 전송할 때 사용 -->
<input type="hidden" name="h" value="asdf">
<input type="button" value="일반버튼" onclick="a()">
<input type="reset" value="초기화">
<input type="submit" value="데이터전송">
</form>
</body>
</html>
< image >
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
img{
width:200px;
height:200px;
}
</style>
<script>
let arr = ["a.png", "b.png", "naver_logo.png"];
let cnt = 0;
function a(){
document.img1.src = "../img/" + arr[cnt%3];
cnt++;
}
</script>
</head>
<body>
<img name="img1" src="../img/naver_logo.png">
<input type="button" value="next" onclick="a()">
</body>
</html>
setTimeout(함수명, 딜레이) -- 딜레이 시간이 지난 뒤 함수명으로 지정한 함수를 호출해줌. (반복 없음)
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
img{
width:200px;
height:200px;
}
</style>
<script>
let arr = ["a.png", "b.png", "naver_logo.png"];
let cnt = 0;
function b(){ // 1초마다 이미지 바뀜
document.img1.src = "../img/" + arr[cnt%3];
cnt++;
/* setTimeout(함수명, 딜레이): 딜레이 시간이 지난 뒤 함수명으로 지정한 함수를 호출해줌 */
/* 반복기능 없음. */
/* 1000 = 1초 */
setTimeout(b, 1000);
}
/* 페이지 로드 되자마자 실행 */
window.onload=function(){
b();
}
</script>
</head>
<body>
<img name="img1" src="../img/naver_logo.png">
<!-- <input type="button" value="next" onclick="a()"> -->
</body>
</html>
https://www.w3schools.com/js/js_htmldom.asp
JavaScript HTML DOM
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
< DOM >
: Document Object Model (문서 객체 모델)
-- HTML 문서의 모든 요소에 접근 및 변경 가능
- 웹페이지가 로드되면 브라우저는 페이지의 DOM을 생성함.
객체의 HTML DOM 트리
- 페이지의 모든 HTML 요소 및 속성을 변경할 수 있음.
- 페이지의 모든 CSS 스타일을 변경할 수 있음.
- 기존 HTML 요소 및 속성을 제거할 수 있음.
- 새로운 HTML 요소 및 속성을 추가할 수 있음.
- 페이지의 모든 기존 HTML 이벤트에 반응함. (이벤트 핸들러..?)
- 페이지에서 새로운 HTML 이벤트 생성 가능.
1. 요소 추출 메서드 - document.getElement
document.getElementById("아이디"); -- 요소 1개 반환
document.getElimentsByTagName("태그명"); -- 동일한 태그명을 찾아서 배열에 담아 반환
document.getElimentsByClassName("클래스명"); -- 동일한 클래스명을 찾아서 배열에 담아 반환
요소.속성 = 값;
alert(요소.속성);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
window.onload = function() {
let img = document.getElementById("img1");
let txt = "";
txt += "src:" + img.src + "<br/>";
txt += "id:" + img.id + "<br/>";
txt += "style.width:" + img.style.width + "<br/>";
txt += "style.height:" + img.style.height + "<br/>";
let res = document.getElementById("res");
res.innerHTML = txt;
let t1 = document.getElementById("t1");
t1.value = "hello dom";
}
</script>
</head>
<body>
<div id="res"></div>
<img src="../img/naver_dog.gif" id="img1"
style="width: 400px; height: 150px">
<input type="text" id="t1">
</body>
</html>
2. innerHTML ★
: 여는 태그<>와 닫는 태그</> 사이의 값
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function a() { // id로 검색
let id_h = document.getElementById("h"); // <h3 id="h">~A~</h3>
let res = document.getElementById("res"); // <div id="res"></div>
res.innerHTML = id_h.innerHTML; // <div>~A~</div>
}
function b() { // 태그명으로 검색
// 태그명이 h3인 요소를 모두 추출. (하나밖에 없어도)무조건 배열로 반환.
let arr = document.getElementsByTagName("h3");
let txt = "";
for(i = 0; i < arr.length; i++){
txt += arr[i].innerHTML; // txt에 사잇값을 연결
// txt += arr[i].innerHTML + "<br/>"; // txt에 사잇값을 다음줄에 연결
}
// id가 res인 요소의 내용으로 txt 출력
let res = document.getElementById("res");
res.innerHTML = txt;
}
function c() { // 클래스명으로 검색
let arr = document.getElementsByClassName("c1");
let txt = "";
for(i = 0; i < arr.length; i++){
txt += arr[i].innerHTML;
}
let res = document.getElementById("res");
res.innerHTML = txt;
}
</script>
</head>
<body>
<div id="res"></div>
<input type="button" value="id로 검색" onclick="a()">
<input type="button" value="태그명으로 검색" onclick="b()">
<input type="button" value="클래스명으로 검색" onclick="c()">
<h3 id="h">~A~</h3>
<h3 class="c1">~B~</h3>
<h3>~C~</h3>
<h3 class="c1">~D~</h3>
<h3>~E~</h3>
<h3 class="c1">~F~</h3>
</body>
</html>
3. 요소 속성값 - .attribute
요소.attribute = 새 값;
요소.setAttribute("속성명", "값"); -- 속성값 변경 (요소.속성=값)
요소.getAttribute("속성명"); -- 속성값 반환 (alert 요소.속성)
4. 요소 생성(createElement) / 추가(appendChild) / 삭제 (removeChild) / .on이벤트
1) 요소 생성
document.createElement("태그명");
let cnt = 1;
function mkDiv(writer, pwd, content) {
let newDiv = document.createElement("div"); //새 <div></div> 태그 생성
newDiv.id = "d_" + cnt++; // 생성한 div에 id 지정. d_cnt
let html = ""; //생성한 div에 출력될 내용 담을 변수
html += "writer: " + writer + "<br/>";
html += "content: " + content + "<br/>";
html += "<input type='button' value='수정'>";
html += "<input type='button' value='삭제'>";
newDiv.innerHTML = html;
//<div>writer content 수정버튼 삭제버튼</div> 와 같음.
return newDiv;
}
2) 요소 추가
부모요소.appendChild(새 요소); -- 새 요소를 부모요소의 자식요소로 추가
- <body>에 있는 <table t1>이 부모 요소.
- <div id="list"></div>에 새로 추가된 el이 자식 요소.
<head>
<script>
function a(){
let writer = f.writer.value;
let pwd = f.pwd.value;
let content = f.content.value;
let el = mkDiv(writer, pwd, content); // newDiv를 el에 담음
let list = document.getElementById("list");
list.appendChild(el);
}
</script>
</head>
<body>
<h3>방명록</h3>
<form name="f">
<table id="t1">
<tr><th>작성자</th><td><input type="text" name="writer" id="writer"></td></tr>
<tr><th>글 비밀번호</th><td><input type="password" name="pwd" id="pwd"></td></tr>
<tr><th>내용</th><td><input type="text" name="content" id="content"></td></tr>
<tr><th>작성</th><td><input type="button" value="작성" onclick="a()"></td></tr>
</table>
</form>
<div id="list"></div>
</body>
3) 요소 삭제
부모요소.removeChild(삭제할 요소);
4) 요소에 이벤트 핸들러 추가
요소.on이벤트 = 함수
click (클릭 이벤트) -- onclick
load (페이지 열리자마자 발생) -- onload
focus (포커스 획득) -- onfocus
blur (포커스 빼앗김) -- onblur
change (입력값이 변경된 뒤 포커스 잃었을 때) -- onchange
mouseover (영역에 마우스가 들어갔을 때) -- onmouseover
mouseout (영역 밖으로 마우스가 나갔을 때) -- onmouseout
keydown (키보드 누를때) -- onkeydown
keyup (키보드 눌렀다 땠을 때) --onkeyup
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
let cnt = 1;
function add(){
let btn = document.createElement("input");
btn.type = "button";
btn.value = "btn" + cnt;
btn.id = "b" + cnt;
btn.onclick = handler; //핸들러 등록만. click 이벤트 발생하면 호출됨.
// handler(); 하면 add()호출될 때 같이 호출됨.
cnt++;
let list = document.getElementById("list");
list.appendChild(btn);
}
function del() {
if(cnt<2) {
alert("삭제할 버튼 없음");
return;
}
let num = cnt-1; // 마지막으로 생성된 버튼 번호
let delBtn = document.getElementById("b" + num);
let list = document.getElementById("list");
list.removeChild(delBtn);
cnt--;
}
function handler(){
// this : 이벤트 발생한 타겟 객체
alert(this.id + "버튼눌림");
}
</script>
</head>
<body>
<input type="button" value="버튼추가" onclick="add()">
<input type="button" value="버튼삭제" onclick="del()">
<div id="list"></div>
</body>
</html>