-
jQuery 제이쿼리 기초프로그래밍/jQuery 제이쿼리 2021. 10. 27.반응형
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
들어가기 앞서 제이쿼리 사용을 위해서 script 한줄을 추가 해준다.
다른 파일에서도 제이쿼리 사용을 하려면 추가 해야함.
<%@ page contentType="text/html; charset=UTF-8"%> <%@ page trimDirectiveWhitespaces="true" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> // DOM이 로드 될 때 실행 /* // 이벤트 핸들러 프로퍼티 방식 // 테스트-2만 실행됨 window.onload = function() { console.log("테스트-1"); }; window.onload = function() { console.log("테스트-2"); }; */ /* // addEventListener로 이벤트 등록 // 둘다 실행됨 window.addEventListener("load", function() { console.log("테스트-1"); }); window.addEventListener("load", function() { console.log("테스트-2"); }); */ /* // jquery로 실행하기 // 둘다 실행하기 jQuery(document).ready(function() { console.log("테스트-1"); }); jQuery(document).ready(function() { console.log("테스트-2"); }); */ /* // jQuery(document).ready(function(){}); 을 짧게 표현이 가능함. jQuery(function(){ console.log("테스트-1"); }); jQuery(function(){ console.log("테스트-2"); }); */ /* // jQuery를 $로 표현 가능함. $(function(){ console.log("테스트-1"); }); $(function(){ console.log("테스트-2"); }); */ /* $(document).ready(function(){ // DOM 객체만 로드되면 바로 실행 console.log("테스트-1"); }); $(window).on("load", function(){ // 해당 페이지의 모든 외부 리소스(css, 이미지 등등)가 로드 된 이후에 실행 console.log("테스트-2"); }); */ $(function(){ $(document.body).css("background", "#ff0"); }); </script> </head> <body> <h3>jQuery Core 예제</h3> <p> jQuery(elements), $(elements) </p> <p> $() = $(document).ready() = jQuery() = jQuery(document).ready() </p> </body> </html>
제이쿼리는 HTML에 관여할 수 있음
예를 들면 HTML내 모든 p 태그의 style을 바꾼다던지 일부 태그들에게만 속성이나 값을 적용하거나 준다던지
이런 과정이 매우 쉽게 가능함.
제이쿼리를 사용하기 위해서는 자바 스크립트 처럼 script 코드를 열어야 한다.
제이쿼리 사용을 위한 총 4가지의 방법
$() = $(document).ready() = jQuery() = jQuery(document).ready()
제이쿼리 예시
$(function(){ $(document.body).css("background", "#ff0"); });
- DOM이 로드 되면 (document.body)의 css를 바꾸겠다 라는 뜻
<%@ page contentType="text/html; charset=UTF-8"%> <%@ page trimDirectiveWhitespaces="true" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> * { padding: 0; margin: 0; box-sizing: border-box; } body { font-size: 14px; font-family: 맑은 고딕, 나눔고딕, 돋움, sans-serif; } a { color : #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } h3 { margin: 10px; } span, label { display: block; } .box { width: 350px; min-height: 50px; margin: 20px auto; padding: 15px; border: 3px dotted gray; } </style> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> // 실행 안되는 이유 : DOM이 준비되지 않아서 // $("p").css("border", "1px solid #777"); // DOM이 로딩 되었을때 실행 $(function(){ // 모든 요소 $("*").css({color:"#333", "font-size":"13px"}); // 태그 선택자 $("p").css("border", "2px dashed #333"); // id 선택자 $("#layout1").css({width:'300px', padding:'10px', border:'2px solid green'}); // class 선택자 $(".red").css("color", "red"); // AND 연산 $("label.underline").css("text-decoration", "underline"); // 바로 아래 자식 하나 $("div > label").css("color", "tomato"); // 모든 자식(손자도 포함) $("div label").css("background", "#ff0"); // 인접 형제. 바로 다음 형제 하나 $("label + span").css("border", "1px dashed red"); // 다음에 나오는 일반 형제 $("label ~ span").attr("title", "과목"); // 속성 추가 title 속성은 마우스 올리면 나오는 텍스트임 }); </script> </head> <body> <h3>selector</h3> <div class="box"> <div id="layout1"> <label>프로그래밍</label> <span class="red">자바</span> <span>C언어</span> <span class="underline">코틀린</span> <p> <label class="red underline">데이터베이스</label> <span>오라클</span> <span>mysql</span> <span>빅데이터</span> </p> </div> <div id="layout2"> <label>웹</label> <span>HTML</span> <span>CSS</span> <span>javascript</span> <p> <label>웹프로그래밍</label> <span>JSP</span> <span>PHP</span> <span>ASP.NET</span> </p> <p> <span>React</span> <label>기타</label> <span>jquery</span> </p> </div> </div> </body> </html>
css의 속성 여러개를 바꿀때는 {} 괄호를 열어야 한다.
$("*").css({color:"#333", "font-size":"13px"});
속성 하나만 바꿀 경우 () 소괄호 만으로도 충분
$("p").css("border", "2px dashed #333");
<%@ page contentType="text/html; charset=UTF-8"%> <%@ page trimDirectiveWhitespaces="true" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> * { padding: 0; margin: 0; box-sizing: border-box; } body { font-size: 14px; font-family: 맑은 고딕, 나눔고딕, 돋움, sans-serif; } a { color : #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } h3 { margin: 10px; } .box { width: 350px; min-height: 50px; margin: 20px auto; padding: 15px; border: 3px dotted gray; } .box span, .box labe { display: block; } </style> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> // 실행 안되는 이유 : DOM이 준비되지 않아서 // $("p").css("border", "1px solid #777"); // DOM이 로딩 되었을때 실행 $(function(){ // span 태그의 글자색을 tomato로 $("span").css("color", "tomato"); // span 태그와 label 태그의 글자에 밑줄 $("span, label").css("text-decoration", "underline"); // div1 아이디의 글자색을 blue $("#div1").css("color", "blue"); // div2 아이디의 글자를 진하게 $("#div1").css("font-weight", "700"); // c1 클래스의 배경색을 yellow로 $(".c1").css("background", "yellow"); // input 요소 중 name=subject 인 요소 $("input[name=subject]").css("background", "#eee"); // form의 input 요소중 name 속성을 가진 요소 $("form input[name]").css("border", "none"); // form의 input 요소중 type=text와 type=password인 요소 $("form input[type=text], form input[type=password]").css("border-bottom", "1px solid blue"); // form의 input 요소중 name 속성 값이 'a'로 시작하는 요소 $("form input[name^=a]").css("border-right", "3px solid red"); // form의 input 요소중 title 속성 값이 '버튼'으로 끝나는 요소 $("form input[title$='버튼']").css("background", "green"); // form의 input 요소중 name 속성 값이 'x'가 포함된 요소 $("form input[name*=x]").css("border-left", "3px solid black"); // form의 input 요소중 title 속성 값에 '내용'이라는 단어가(띄어쓰기로 구분) 들어간 요소 $("form input[title~='내용']").css("background", "yellow"); }); </script> </head> <body> <h3>selector</h3> <div class="box"> <div id="div1">테스트 1</div> <div id="div2" class="c1">테스트 2</div> <span>테스트 3</span> <span>테스트 4</span> <div id="div3" class="c1">테스트 5</div> <span class="c1">테스트 6</span> <span class="c2">테스트 7</span> </div> <hr> <div class="box"> <p><input type="text" name="subject" title="과목 입력"></p> <form action=""> <p><input type="text" name="subject" title="과목 입력"></p> <p><input type="text" name="ax1" title="1장 제목 입력"></p> <p><input type="text" name="as1" title="1장 내용 입력"></p> <p><input type="text" name="bs1" title="2장 제목 입력"></p> <p><input type="text" name="bx2" title="2장 내용 입력"></p> <p><input type="password" name="pwd" title="패스워드 입력"></p> <p><input type="file" name="selectFile"> </p> <p> <input type="button" value="입력완료" title="입력 버튼"> <input type="reset" value="다시입력" title="리셋 버튼"> </p> </form> </div> </body> </html>
- focus, blur 이벤트 주기
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> *{ padding: 0; margin: 0; } body { font-size:14px; font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } h3 { margin: 10px; } .btn { color:#333; font-weight:500; border:1px solid #ccc; background-color:#fff; text-align:center; cursor:pointer; padding:3px 10px 5px; border-radius:4px; font-family:"Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif; } .btn:active, .btn:focus, .btn:hover { background-color:#e6e6e6; border-color: #adadad; color: #333; } textarea:focus, input:focus{ outline: none; } .boxTF { border:1px solid #999; padding:3px 5px 5px; border-radius:4px; background-color:#fff; font-family:"Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif; } .box{ box-sizing: border-box; width: 500px; min-height: 50px; margin: 20px auto; border: 3px dotted gray; padding: 15px; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(function(){ $("form input + span").hide(); $("form input[type=text]").css("border", "1px solid #aaa"); // focus 이벤트 $("form input").not($(":button")).focus(function(){ $(this).css("border", "1px solid #f28011"); // 이벤트를 발생시킨 바로 다음 형제 중에서 span 태그 $(this).next("span").show(); }); // blur 이벤트 $("form input").not($(":button")).blur(function(){ $(this).css("border", "1px solid #aaa"); // 이벤트를 발생시킨 바로 다음 형제 중에서 span 태그 $(this).next("span").hide(); }); }); </script> </head> <body> <h3>selectors 예제</h3> <div class="box"> <form> <p> <input type="text" name="id"> <span>아이디 입력.</span> <span>5~10자 이내</span> </p> <p> <input type="text" name="name"> <span>이름 입력.</span> </p> <p> <input type="text" name="age"> <span>나이 입력.</span> </p> <p> <input type="text" name="birth"> <span>생년월일 입력.</span> </p> <p style="padding: 5px;"> <!-- <button type="button" class="btn"> 등록하기 </button> <button type="button" class="btn"> 등록취소 </button> --> <input type="button" class="btn" value="등록하기"> <input type="button" class="btn" value="등록취소"> </p> </form> </div> </body> </html>
스크립트 분석
$(function(){ $("form input + span").hide(); $("form input[type=text]").css("border", "1px solid #aaa"); // focus 이벤트 $("form input").not($(":button")).focus(function(){ $(this).css("border", "1px solid #f28011"); // 이벤트를 발생시킨 바로 다음 형제 중에서 span 태그 $(this).next("span").show(); }); // blur 이벤트 $("form input").not($(":button")).blur(function(){ $(this).css("border", "1px solid #aaa"); // 이벤트를 발생시킨 바로 다음 형제 중에서 span 태그 $(this).next("span").hide(); }); });
- form 안에 모든 input 태그를 숨길 수 있음
- focus를 통해서 버튼에는 해당 사항 없게 => .not($(":button"))
인풋 박스에만 해당 사항을 주고 => $("form input")
$(this)를 통해 이벤트를 발생시킨 인풋 박스에 css를 적용 시킨다.
그리고 아까 숨겼던 span 태그를 focus일 당시에만 보여준다.
- blur는 반대로 하면 됨
제이쿼리에서만 쓸 수 있는 명령어가 있다.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> *{ padding: 0; margin: 0; } body { font-size:14px; font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } h3 { margin: 10px; } .box{ width: 700px; margin: 30px auto; } .box table { width: 100%; border-collapse: collapse; border-spacing: 0; } .box table tr:first-child{ border-top: 3px solid #777; background: #ccc; } .box table tr{ height: 30px; border-bottom: 1px solid #777; text-align: center; } .box table span{ cursor: pointer; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(function(){ //$("tr:first").css("color", "darkblue"); $("tr:eq(0)").css("color", "darkblue"); // 위에랑 같은 말임 인덱스 0부터 $("tr:odd").css("background", "#efefef"); $("tr:last").css("border-bottom", "2px solid #777"); // 전체 td중 첫번째 td 하나만 // $("td:first").css("background", "yellow"); // tr의 첫번째 자식 // $("td:first-child").css("background", "yellow"); // tr의 마지막 자식 // $("td:first-last").css("background", "yellow"); // n번째 자식 요소(요소의 인덱스는 1부터 0부터 아님) $("td:nth-child(2n+1)").css("background", "yellow"); }); /* -- Filter :eq(n) : 선택한 요소 중에서 인덱스가 n인 요소를 선택. $("ul li:eq(3)") :gt(n) : 선택한 요소 중에서 인덱스가 n보다 큰 요소를 모두 선택. $("ul li:gt(3)") :lt(n) : 선택한 요소 중에서 인덱스가 n보다 작은 요소를 모두 선택. $("ul li:lt(3)") :even : 선택한 요소 중에서 인덱스가 짝수인 요소를 모두 선택. $("tr:even") :odd : 선택한 요소 중에서 인덱스가 홀수인 요소를 모두 선택. $("tr:odd") :first : 선택한 요소 중에서 첫 번째 요소를 선택. $("p:first") :last : 선택한 요소 중에서 마지막 요소를 선택. $("p:last") :animated : 선택한 요소 중에서 애니메이션 효과가 실행 중인 요소를 모두 선택. $(":animated") :header : 선택한 요소 중에서 <h1>부터 <h6>까지의 요소를 모두 선택. $(":header") :lang(언어) : 선택한 요소 중에서 지정한 언어의 요소를 모두 선택. $("p:lang(ko)") :not(선택자) : 선택한 요소 중에서 지정한 선택자와 일치하지 않는 요소를 모두 선택. $("input:not(:empty)") :root : 선택한 요소 중에서 최상위 루트 요소를 선택. $(":root") target : 선택한 요소 중에서 웹 페이지 URI의 fragment 식별자와 일치하는 요소를 모두 선택. $("a[target='_blank']") :contains(텍스트) : 선택한 요소 중에서 지정한 텍스트를 포함하는 요소를 모두 선택. $(":contains('Hello')") :has(선택자) : 선택한 요소 중에서 지정한 선택자와 일치하는 자손 요소를 갖는 요소를 모두 선택. $("p:has(span)") :empty : 선택한 요소 중에서 자식 요소를 가지고 있지 않은 요소를 모두 선택. $(":empty") :parent : 선택한 요소 중에서 자식 요소를 가지고 있는 요소를 모두 선택. $(":parent") -- 자식 필터 :first-child : 셀렉터에 해당하는 모든 요소 중 첫번째 자식인 요소를 선택. :last-child : 셀렉터에 해당하는 모든 요소 중 마지막 자식인 요소를 선택. :nth-child(n) : 셀렉터에 해당하는 모든 요소 중 앞에서 n번째 자식인 요소를 선택. n은 0부터 대입하고, 요소의 index는 1부터 시작 :nth-child(even/odd) : even, odd에 해당하는 자식들과 일치. :nth-last-child(n) : 셀렉터에 해당하는 모든 요소 중 뒤에서 n번째 자식인 요소를 선택. :only-child : 자신이 부모 요소의 유일한 자식인 모든 요소와 일치. */ </script> </head> <body> <h3>selectors 예제</h3> <div class="box"> <table> <tr> <th width="80">학번</th> <th width="100">이름</th> <th width="80">국어</th> <th width="80">영어</th> <th width="80">수학</th> <th width="80">총점</th> <th width="80">평균</th> <th>변경</th> </tr> <tr> <td>1001</td> <td>너자바</td> <td>80</td> <td>70</td> <td>90</td> <td>240</td> <td>80</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1002</td> <td>서블릿</td> <td>75</td> <td>80</td> <td>60</td> <td>225</td> <td>75</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1003</td> <td>스프링</td> <td>80</td> <td>100</td> <td>90</td> <td>270</td> <td>90</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1004</td> <td>오라클</td> <td>85</td> <td>85</td> <td>85</td> <td>255</td> <td>85</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1005</td> <td>리액트</td> <td>80</td> <td>70</td> <td>60</td> <td>210</td> <td>70</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1006</td> <td>홍자바</td> <td>85</td> <td>85</td> <td>85</td> <td>255</td> <td>85</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1007</td> <td>이순신</td> <td>70</td> <td>70</td> <td>70</td> <td>210</td> <td>70</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1008</td> <td>이자바</td> <td>100</td> <td>100</td> <td>100</td> <td>300</td> <td>100</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1009</td> <td>가나다</td> <td>95</td> <td>100</td> <td>90</td> <td>285</td> <td>95</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1010</td> <td>하하하</td> <td>90</td> <td>90</td> <td>90</td> <td>270</td> <td>90</td> <td><span>수정</span> | <span>삭제</span></td> </tr> </table> </div> </body> </html>
:eq(n) : 선택한 요소 중에서 인덱스가 n인 요소를 선택. $("ul li:eq(3)") :gt(n) : 선택한 요소 중에서 인덱스가 n보다 큰 요소를 모두 선택. $("ul li:gt(3)") :lt(n) : 선택한 요소 중에서 인덱스가 n보다 작은 요소를 모두 선택. $("ul li:lt(3)") :even : 선택한 요소 중에서 인덱스가 짝수인 요소를 모두 선택. $("tr:even") :odd : 선택한 요소 중에서 인덱스가 홀수인 요소를 모두 선택. $("tr:odd") :first : 선택한 요소 중에서 첫 번째 요소를 선택. $("p:first") :last : 선택한 요소 중에서 마지막 요소를 선택. $("p:last") :animated : 선택한 요소 중에서 애니메이션 효과가 실행 중인 요소를 모두 선택. $(":animated") :header : 선택한 요소 중에서 <h1>부터 <h6>까지의 요소를 모두 선택. $(":header") :lang(언어) : 선택한 요소 중에서 지정한 언어의 요소를 모두 선택. $("p:lang(ko)") :not(선택자) : 선택한 요소 중에서 지정한 선택자와 일치하지 않는 요소를 모두 선택. $("input:not(:empty)") :root : 선택한 요소 중에서 최상위 루트 요소를 선택. $(":root") target : 선택한 요소 중에서 웹 페이지 URI의 fragment 식별자와 일치하는 요소를 모두 선택. $("a[target='_blank']") :contains(텍스트) : 선택한 요소 중에서 지정한 텍스트를 포함하는 요소를 모두 선택. $(":contains('Hello')") :has(선택자) : 선택한 요소 중에서 지정한 선택자와 일치하는 자손 요소를 갖는 요소를 모두 선택. $("p:has(span)") :empty : 선택한 요소 중에서 자식 요소를 가지고 있지 않은 요소를 모두 선택. $(":empty") :parent : 선택한 요소 중에서 자식 요소를 가지고 있는 요소를 모두 선택. $(":parent") -- 자식 필터 :first-child : 셀렉터에 해당하는 모든 요소 중 첫번째 자식인 요소를 선택. :last-child : 셀렉터에 해당하는 모든 요소 중 마지막 자식인 요소를 선택. :nth-child(n) : 셀렉터에 해당하는 모든 요소 중 앞에서 n번째 자식인 요소를 선택. n은 0부터 대입하고, 요소의 index는 1부터 시작 :nth-child(even/odd) : even, odd에 해당하는 자식들과 일치. :nth-last-child(n) : 셀렉터에 해당하는 모든 요소 중 뒤에서 n번째 자식인 요소를 선택. :only-child : 자신이 부모 요소의 유일한 자식인 모든 요소와 일치.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> *{ padding: 0; margin: 0; } body { font-size:14px; font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } h3 { margin: 10px; } .box{ width: 700px; margin: 30px auto; } .box table { width: 100%; border-collapse: collapse; border-spacing: 0; } .box table tr:first-child{ border-top: 3px solid #777; background: #ccc; } .box table tr{ height: 30px; border-bottom: 1px solid #777; text-align: center; } .box table span{ cursor: pointer; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(function(){ $("table.tc td:empty").css("background", "yellow"); $(".tc td:contains('오라클')").css("color", "red"); // td $(".tc td:contains('스프링')").parent().css("background", "pink"); // tr 줄 전체 parent로 그 속성의 부모에게도 적용 // $("table.tc tr:eq(1)").css("background", "tomato"); // $("table.tc tr:gt(5)").css("background", "#eee"); // tr의 각 3,6,9.. 번째 td // $("table.tc td:nth-child(3n)").css("background", "tomato"); $("table.tc td").each(function(index){ // 모든 td, each는 반복문 if(index != 0 && index%6 == 0) { $(this).css("background", "lightblue"); } }); }); </script> </head> <body> <h3>selectors 예제</h3> <div class="box"> <table class="tc"> <tr> <th width="80">학번</th> <th width="100">이름</th> <th width="80">국어</th> <th width="80">영어</th> <th width="80">수학</th> <th width="80">총점</th> <th width="80">평균</th> <th>변경</th> </tr> <tr> <td>1001</td> <td>너자바</td> <td>80</td> <td>70</td> <td>90</td> <td>240</td> <td>80</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1002</td> <td>서블릿</td> <td>75</td> <td>80</td> <td>60</td> <td>225</td> <td>75</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1003</td> <td>스프링</td> <td>80</td> <td>100</td> <td>90</td> <td>270</td> <td>90</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1004</td> <td>오라클</td> <td>85</td> <td>85</td> <td>85</td> <td>255</td> <td>85</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1005</td> <td>리액트</td> <td>80</td> <td>70</td> <td>60</td> <td>210</td> <td>70</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1006</td> <td>홍자바</td> <td>85</td> <td>85</td> <td>85</td> <td>255</td> <td>85</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1007</td> <td>이순신</td> <td>70</td> <td>70</td> <td>70</td> <td>210</td> <td>70</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1008</td> <td>이자바</td> <td>100</td> <td>100</td> <td>100</td> <td>300</td> <td>100</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1009</td> <td>가나다</td> <td>95</td> <td>100</td> <td>90</td> <td>285</td> <td>95</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1010</td> <td>하하하</td> <td>90</td> <td>90</td> <td>90</td> <td>270</td> <td>90</td> <td><span>수정</span> | <span>삭제</span></td> </tr> <tr> <td>1011</td> <td>후후후</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td><span>수정</span> | <span>삭제</span></td> </tr> </table> </div> </body> </html>
제이쿼리로 HTML에 속성에 개입하기
값을 주거나 값을 변경
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> *{ padding: 0; margin: 0; } body { font-size:14px; font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } .btn{ color:#333; font-weight:500; border:1px solid #ccc; background-color:#fff; text-align:center; cursor:pointer; padding:3px 10px 5px; border-radius:4px; } ul { list-style: none; } li{ padding: 0; } h3{ margin: 30px; } .box{ box-sizing: border-box; width: 350px; min-height: 50px; margin: 20px auto; border: 3px dotted gray; padding: 15px; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(function(){ $(".btnOk").click(function(){ // var name = $(".std").html() // html 소스 반환 innerHTML속성 var name = $(".std").text() // 텍스트만 반환 // 속성값 가져오기 var num = $(".std").attr("data-num"); // document.getElementById("score").value = 90; $("#score").val(90); // value에 값 넣기 // value 값 가져오기 var subject = $("#subject").val(); var score = $("#score").val(); var s = "<p>학번 : <b>" + num + "</b></p>"; s += "<p>이름 : <b>" + name + "</b></p>"; s += "<p>과목 : <b>" + subject + "</b></p>"; s += "<p>점수 : <b>" + score + "</b></p>"; // 텍스트 설정 // $("#layout").text(s); // html 콘텐츠 설정 $("#layout").html(s); }); }); /* -- 선택된 요소 접근 .html() : 해당 요소의 HTML 콘텐츠를 반환하거나 설정한다. .text() : 해당 요소의 텍스트 콘텐츠를 반환하거나 설정한다. .val() : <form>요소의 값을 반환하거나 설정한다 .attr() : 해당 요소의 명시된 속성의 속성값을 반환하거나 설정한다. .width() : 선택한 요소 중에서 첫 번째 요소의 너비를 픽셀 단위의 정수로 반환하거나 설정한다. .height() : 선택한 요소 중에서 첫 번째 요소의 높이를 픽셀 단위의 정수로 반환하거나 설정한다. .position() : 선택한 요소 중에서 첫 번째 요소에 대해 특정 위치에 존재하는 객체를 반환한다.(getter 메소드) -- 메소드 체이닝(method chaining) 여러 개의 메소드가 연속으로 호출되는 것 예 : $("ul").find("li").eq(1).append("자바"); */ </script> </head> <body> <h3>선택된 요소 접근</h3> <div style="margin: 20px;"> <button type="button" class="btn btnOk"> 확인 </button> </div> <hr> <div class="box"> <p> <!-- data-* 개발자에 의해 만들어진 속성(내가 data-num이라는 속성을 만들었음) --> <span class="std" data-num="1"><b>홍길동</b></span> </p> <p> <input type="text" id="subject" value="자바"> </p> <p> <input type="text" id="score"> </p> </div> <div class="box"> <p>결과</p> <div id="layout"></div> </div> </body> </html>
-- 선택된 요소 접근 .html() : 해당 요소의 HTML 콘텐츠를 반환하거나 설정한다. .text() : 해당 요소의 텍스트 콘텐츠를 반환하거나 설정한다. .val() : <form>요소의 값을 반환하거나 설정한다 .attr() : 해당 요소의 명시된 속성의 속성값을 반환하거나 설정한다. .width() : 선택한 요소 중에서 첫 번째 요소의 너비를 픽셀 단위의 정수로 반환하거나 설정한다. .height() : 선택한 요소 중에서 첫 번째 요소의 높이를 픽셀 단위의 정수로 반환하거나 설정한다. .position() : 선택한 요소 중에서 첫 번째 요소에 대해 특정 위치에 존재하는 객체를 반환한다.(getter 메소드) -- 메소드 체이닝(method chaining) 여러 개의 메소드가 연속으로 호출되는 것 예 : $("ul").find("li").eq(1).append("자바");
제이쿼리로 HTML에 요소 추가 (첫번째 위치, 마지막 위치)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <style type="text/css"> *{ padding: 0; margin: 0; } body { font-size:14px; font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif; } a { color: #000; text-decoration: none; } a:hover, a:active { color: tomato; text-decoration: underline; } ul { list-style: none; } li{ padding: 0; } h3{ margin: 30px; } .box{ box-sizing: border-box; width: 350px; min-height: 50px; margin: 20px auto; border: 3px dotted gray; padding: 15px; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(function(){ // 마지막에 새로운 요소 추가 $(".box1 ul").append("<li>C/C++</li>"); $("<li>HTML 5</li>").appendTo(".box2 ul"); // 첫번째에 새로운 요소 추가 $(".box3 ul").prepend("<li>JSP/SERVELT</li>"); $("<li>ORACLE</li>").prependTo(".box4 ul"); }); /* -- 요소 추가 : 기존 요소의 내부에 추가 .append() : 선택된 요소의 마지막에 새로운 요소나 콘텐츠를 추가한다. .prepend() : 선택된 요소의 첫번째에 새로운 요소나 콘텐츠를 추가한다. .appendTo() : 선택된 요소를 해당 요소의 마지막에 추가한다. .prependTo() : 선택된 요소를 해당 요소의 첫번째에 추가한다. */ </script> </head> <body> <h3>조작(Manipulation)</h3> <div class="box box1"> <ul> <li>자바</li> <li>스프링</li> </ul> </div> <div class="box box2"> <ul> <li>javascript</li> <li>css</li> </ul> </div> <div class="box box3"> <ul> <li>ASP.NET</li> <li>PHP</li> </ul> </div> <div class="box box4"> <ul> <li>MariaDB</li> <li>MySQL</li> </ul> </div> </body> </html>
반응형'프로그래밍 > jQuery 제이쿼리' 카테고리의 다른 글
제이쿼리 - 기초(4) (0) 2021.10.30 제이쿼리 - 기초(3) / 이벤트 (0) 2021.10.30 제이쿼리 - 기초(2) (0) 2021.10.29 제이쿼리 - each 반복문 (0) 2021.10.29 제이쿼리 - 애니메이션 처럼 보이게 만들기 (0) 2021.10.29