본문 바로가기

Jquery

[211103] 제이쿼리 기초

제이쿼리 : 자바스크립트 기반의 라이브러리이다. 

자바스크립트로 구현 가능한 것은 다 제이쿼리에서도 가능하다. (편의성을 위해 만들어짐, 단 라이브러리를 통해 실행되므로 자바스크립트만 사용하는 것에비해 속도가 느리다.)

 

객체 검색(선택)

1. 자바스크립트 방식 

  • document.getElementById(...)
  • document.getElementsByTagName(...)
  • document.getElementsByClassName(...)
  • document.getElementsByName(...)

2. 제이쿼리 방식

  • $("CSS 선택자")
  • ID 선택자
  • 태그 선택자
  • 클래스 선택자
  • 속성 선택자

객체 탐색

1. 자바스크립트 방식

  • 부모 탐색
  • 자식 탐색
  • 형제 탐색

2. 제이쿼리 방식

  • 부모 탐색
  • .parent()
  • .parents()
  • 자식 탐색
  • .children()
  • 형제 탐색
  • .siblings()
  • .next()
  • .nextAll()
  • .prev()
  • .prevAll()

이벤트

1. 자바스크립트 방식

  • document.getElementById("id_title").addEventListener("click", function() {
        console.log("클릭!"); });

 

2. 제이쿼리 방식

  • $("#id_title").on("mouseover", function() { console.log("마우스오버") });

 

.on() 메소드를 이용하여 이벤트 핸들러와 바인딩(연결)한다.

바인딩 하지 않고 바로

$("#id_title").mouseleave(function() { console.log("마우스리브") });  

.on() 메소드를 이용하면 이벤트 핸들러 하나에 여러개의 이벤트 설정 가능

$("#id_title").on("mouseover mouseleave", function() { console.log("마우스오버 또는 마우스리브 되었습니다.") });

 

클래스 추가

1. 자바스크립트 방식

item.classList.add();

 

2. 제이쿼리 방식

item.addClass();

 


jquery-3.6.0.min.js
0.09MB

 

제이쿼리 문서 저장 후 

<!DOCTYPE
html>

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
                  <!-- 다음과 같이 등록하여 사용 (파일 위치 정확히 작성) -->

    <script type="text/javascript" src="/static/js/jquery-3.6.0.min.js"></script>
</head>
<body>
   
<h1 id="id_title" name="name_title" class="class_title">Hello</h1>
    <h2>Hello</h2>
    <h3>Hello</h3>
    <h4>Hello</h4>

    <div>
        <input type="text" name="username">
    </div>
    <div>
        <input type="password" name="password">
    </div>

</body>
</html>
$("#id_title").text();
'Hello'
$("h1").text();
'Hello'


$("#id_title")
S.fn.init [h1#id_title.class_title]
$(".class_title");
S.fn.init [h1#id_title.class_title, prevObject: S.fn.init(1)]

css 선택자 활용하는 것이기 때문에 name으로는 다음과 같이 찾아야 함

$("input[name=password]")[0].value;  <- 속성 선택자 사용

'abcd'

요소가 2개일 경우 배열형식으로 추출

$("input");
S.fn.init(2) [input, input, prevObject: S.fn.init(1)]
$("input")[0];


input 상자에 값 직접 입력한 뒤

$("input")[0].value;
'1234'
$("input")[1].value;
'abcd'


 

$("input").first();       <-첫번째 input

S.fn.init [input, prevObject: S.fn.init(2)] 

  1. 0: input
  2. length: 1
  3. prevObject: S.fn.init(2) [input, input, prevObject: S.fn.init(1)]
  4. [[Prototype]]: Object(0)

$("input").last();        <-2번째 input

S.fn.init [input, prevObject: S.fn.init(2)]

  1. 0: input
  2. length: 1
  3. prevObject: S.fn.init(2) [input, input, prevObject: S.fn.init(1)]
  4. [[Prototype]]: Object(0)

 

 

.eq() 제이쿼리로 활용할수있는 객체로 반환 

$("input").eq(0);
S.fn.init [input, prevObject: S.fn.init(2)]
$("input").eq(1);
S.fn.init [input, prevObject: S.fn.init(2)]

 

Dom으로 반환 

$("input")[0];

<input type="text" name="username"> 

 

not() name이 패스워드가 아닌 것 

$("input").not("[name=password]");
S.fn.init [input, prevObject: S.fn.init(2)]

  1. 0: input
  2. length: 1
  3. prevObject: S.fn.init(2) [input, input, prevObject: S.fn.init(1)]
  4. [[Prototype]]: Object(0)

 

parent, parents input 요소의 부모, 조상 찾기

$("[name=password]").parent();
S.fn.init [div, prevObject: S.fn.init(1)]  <-부모

 

$("[name=password]").parents();
S.fn.init(3) [div, body, html, prevObject: S.fn.init(1)]   <-조상들까지

 

children div 자식 찾기

$("div")
S.fn.init(2) [div, div, prevObject: S.fn.init(1)]    <-div 총 2개
$("div").children();
S.fn.init(2) [input, input, prevObject: S.fn.init(2)]    <-dic 자식요소 총 2개

 

 

siblings h1 요소의 형제 찾기 (형제 노드(sibling node) : 부모가 같은 노드)

$("h1");
S.fn.init [h1#id_title.class_title, prevObject: S.fn.init(1)]
$("h1").siblings();
S.fn.init(6) [h2, h3, h4, div, div, script, prevObject: S.fn.init(1)]

 

h2 요소의 형제 찾기

$("h2").siblings();
S.fn.init(6) [h1#id_title.class_title, h3, h4, div, div, script, prevObject: S.fn.init(1)]

 

h3 요소의 형제 찾기

$("h3").siblings();
S.fn.init(6) [h1#id_title.class_title, h2, h4, div, div, script, prevObject: S.fn.init(1)]

 

next, prev 로 형제요소 하나씩 찾기 (다음요소, 이전요소)

$("h1").next();
S.fn.init [h2, prevObject: S.fn.init(1)]

$("h2").next();
S.fn.init [h3, prevObject: S.fn.init(1)]
$("h3").next();
S.fn.init [h4, prevObject: S.fn.init(1)]


$("h1").prev();
S.fn.init [prevObject: S.fn.init(1)]
$("h2").prev();
S.fn.init [h1#id_title.class_title, prevObject: S.fn.init(1)]
$("h3").prev();
S.fn.init [h2, prevObject: S.fn.init(1)]

 

nextAll, prevAll 로 형제요소 여러개 찾기 (다음요소, 이전요소)

$("h2").nextAll();
S.fn.init(5) [h3, h4, div, div, script, prevObject: S.fn.init(1)]   <-이전요소인 h1은 안 찾아줌
$("h2").prevAll();
S.fn.init [h1#id_title.class_title, prevObject: S.fn.init(1)]

형제를 다 찾아주느냐 특정 요소의 다음 형제들만 찾아주느냐 이전 형제들만 찾아주느냐 차이

$("h2").siblings();
S.fn.init(6) [h1#id_title.class_title, h3, h4, div, div, script, prevObject: S.fn.init(1)]

 

 

탐색

find() h1의 형제들 중에서 input인 요소(들)

$("h1").siblings().find("input");
S.fn.init(2) [input, input, prevObject: S.fn.init(6)]

 

is() h1의 형제들 중에서 해당 요소 있는지 없는지 true false 반환

$("h1").siblings().is("div");
true
$("h1").siblings().is("input");
false

 

탐색 활용

div 요소 중 0번째 인덱스 div의 html 값 제이쿼리로 반환

$("div").eq(0).html();
'\n        <input type="text" name="username">\n    '

 

h1 요소의 text값 

$("h1").text();
'Hello'

text 값 변경 (화면 출력도 바뀜 Hello -> new Title) 

$("h1").text("new Title"); 

 

html로 효과 지정까지

$("h1").html("<i>new Title2</i>");  <-화면에 이탤릭체로 new Title2 출력

 

 

css 적용

 

css("속성명") css 설정 정보 확인 

$("h1").css("color");      <-color 정보 확인
'rgb(0, 0, 0)'

 

css("속성명", "속성값") css 지정 (단일요소에 지정)
$("h1").css("color", "rgb(255, 0, 0)");  
S.fn.init [h1#id_title.class_title, prevObject: S.fn.init(1)]

 

css({속성명 : 속성값}) css 지정 (다중요소에 지정) : 객체로 만들어서 쓰기(키와 값)  

$("h1").css({"color" : "white", "background-color" : "gray"});
S.fn.init [h1#id_title.class_title, prevObject: S.fn.init(1)]

 

배열로 만들어서 보내기(?)

$("h1").css(["color", "background-color"]);{color: 'rgb(255, 0, 0)', rgb(255, 0, 0): undefined}

 

val() input의 사용자 입력값 지정

$("input");
S.fn.init(2) [input, input, prevObject: S.fn.init(1)]
$("input").first().val();       <- 첫번째 input 박스 값
'1234'
$("input").first().val("1111");   <- 첫번째 input 박스 값 변경
S.fn.init [input, prevObject: S.fn.init(2)]
$("input").last().val();        <- 마지막 input 박스 값
'abcd'
$("input").last().val("2222");      <- 마지막 input 박스 값 변경
S.fn.init [input, prevObject: S.fn.init(2)]

 


attr()

$("input").eq(0).attr("placeholder");
undefined                                                   <- placeholder 지정해주지 않았기 때문에 당연히 값 없음 

$("input").eq(0).attr("placeholder", "아이디입력");  <- placeholder 값 지정
S.fn.init [input, prevObject: S.fn.init(2)]
$("input").eq(0).attr("placeholder");   
'아이디입력'                                                  <-지정한 값 

 

text 포함한 h1 태그 요소 생성

$("<h1>Create Tag</h1>");
S.fn.init [h1]

 

 

$("<h1>Create Tag</h1>");   <- h1요소 생성
S.fn.init [h1]
$("<h1>").text("Create h1 Tag");   <- h1요소 생성하고 텍스트 지정
S.fn.init [h1]
$("<h1>").text("Create h1 Tag")[0];    <- 생성과 동시에 텍스트까지 지정한 h1요소 인덱스로 가져오기 
<h1>​Create h1 Tag​</h1>​
$("<h1>").text("Create h1 Tag").css("color", "red")
S.fn.init [h1]
$("<h1>").text("Create h1 Tag").css("color", "red")[0]
<h1 style=​"color:​ red;​">​Create h1 Tag​</h1>​
$("<h1>").text("Create h1 Tag").css("color", "red").attr("name", "heading1")[0];   <-html 요소 생성 명령, text css attr 순서는 뭘 먼저 지정해도 상관 없음!
<h1 name=​"heading1" style=​"color:​ red;​">​Create h1 Tag​</h1>​

 

배치

prepend & append(선택한 요소 내부), before & after(선택한 요소 외부) 

$("h4").append($("<h1></h1>").text("Create h1 Tag"));    -> 문서에 존재하는 h4 태그 내부의 가장 마지막 위치(append)에 h1요소 만들어서 텍스트까지 넣은 것 배치.

 

삭제

remove : 제거 (삭제)

detach : 떼어내기 (요소의 위치를 이동하고 싶은 경우 사용) 삭제된 요소와 연관된 jQuery 데이터나 이벤트는 유지된다.

 

$("h4").find("h1").first();
S.fn.init [h1, prevObject: S.fn.init(1)]              
$("h4").find("h1")[0];                       
<h1>​Create h1 Tag​</h1>​                      <- DOM 요소 반환
$("h4").find("h1").first().remove();               <- 삭제
S.fn.init [h1, prevObject: S.fn.init(1)]           <- 삭제된 요소 제이쿼리로 반환
$("h4").find("h1").first().detach();
S.fn.init [h1, prevObject: S.fn.init(1)]

 

 

$("h4").find("h1")[0].remove();               <- [0] DOM으로 삭제 시
undefined                                       <- 아무 요소도 반환되지 않음
$("h4").find("h1").eq(0).remove();           <- .first() .eq(0)를 호출하는 래퍼일 뿐, 기능 동일
S.fn.init [h1, prevObject: S.fn.init(1)]  

 


로또 번호 생성기에 제이쿼리 활용 (코드 줄임)

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>로또번호 생성</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0; padding: 0;
        }
        .lotto-area {
            display: flex;
            justify-content: space-evenly;
            margin: 16px auto;
            padding: 32px 16px;
            width: 580px;
            background-color: gainsboro;
            border-radius: 16px;
        }
        .lotto-num {
            font-size: 36px;
            font-weight: blue;
            display: inline-block;
            width: 80px;
            padding: 16px;
            background-color: ghostwhite;
            border-radius: 50%;
            text-align: center;
            color: white;
        }
        .lotto-button {
            margin: 16px auto;
            /* padding: 32px 16px; */
            width: 580px;
            /* border-radius: 16px; */
        }
        .lotto-button button {
            font-size: 24px;
            font-weight: bold;
            width: 100%;
            padding: 16px;
            border-radius: 16px;
            border-style: none;
            background-color: limegreen;
            color: white;
        }
        .lotto-button button:hover {
            box-shadow: 0 0 6px 2px green;
            text-shadow: 0 2px 2px green;
        }
        .lotto-button button:active {
            box-shadow: 2px 2px 6px 2px green;
            text-shadow: 2px 2px 2px green;
        }
        .create-info {
            margin: 16px auto;
            /* padding: 32px 16px; */
            width: 580px;
            /* border-radius: 16px; */
            color: gray;
        }
        .lotto-input {
            margin: 16px auto;
            width: 580px
        }
        .lotto-input input {
            padding: 16px;
            border-radius: 16px;
            width: 100%;
            font-size: 24px;
            font-weight: bold;
            border-style: none;
            outline: 1px solid lightgray;
            background-color: white;
        }
        /*클래스에 배경속성 부여*/
        .bg-1 {
            background-color: goldenrod;
        }
        .bg-2 {
            background-color: dodgerblue;
        }
        .bg-3 {
            background-color: crimson;
        }
        .bg-4 {
            background-color: yellowgreen;
        }
        .bg-5 {
            background-color: lightsteelblue;
        }
    </style>
    <script type="text/javascript" src="/static/js/jquery-3.6.0.min.js"></script> <!--제이쿼리파일먼저로드해야 밑에자바스크립트의 제이쿼리가 실행될것-->
    <script type="text/javascript" src="/static/js/ch06_2.js"></script>
</head>
<body>
    <div id="lotto_number" class="lotto-area">
    </div>
    <div class="lotto-button">
        <button id="create_btn" type="button" onclick="genLotto();">생 성</button>
    </div>
</body>
</html>
function randInt(max, min){  
    if(min === undefined) {
        min = 0;
    }
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function createLottoBall() {
    // var ball = document.createElement("span");
    // // ball.name = "lotNum"; span 속성에는 name 추가 불가
    // ball.className = "lotto-num"
    // return ball;
    var ball = $("<span>");
    ball.attr("class", "lotto-num");  //클래스 속성 지정
    return ball;
}

function genLotto() {
    // var res9 = document.getElementById("res9");
    var lotto = [];

    for(var idx = 0; idx < 6;) {
        var rand = randInt(45, 1);
        if(lotto.indexOf(rand) == -1) {
            lotto[idx] = rand;
            idx++;
        }
    }
    lotto.sort(function(x, y) { return x - y });


    $("#lotto_number").children().remove();   // 모든 자식요소 지우기, 아래처럼 반복문 돌릴 필요 없음

/*
    var len = $("#lotto_number").find("span").length;

    for(var idx = 0; idx < len; idx++) {
        // $("#lotto_number").children[0].remove();  --에러 : 제이쿼리와 자스 섞임
        $("#lotto_number").children().eq(0).remove();
    }
*/

    for(var i = 0; i < lotto.length; i++) {
        var item = createLottoBall();
        item.addClass("bg-" + (Math.floor((lotto[i] - 1) / 10) + 1));
        item.text(lotto[i]);
        $("#lotto_number").append(item);
    }
}

 

일괄 처리

 

로또 번호 뽑으면 모든 텍스트(뽑힌 번호들)를 가져온다. 

$("#lotto_number").children().text();
'2611182527'

 

cf.

$("#input-email").val(); 

'Jquery' 카테고리의 다른 글

[211105] 개인실습 및 정규식  (0) 2021.11.06