본문 바로가기

웹개발 수업/jQuery

[Day +68 / jQuery]기초(5. 객체 탐색, 6. 객체 조작, 7. 이벤트)

210930 목

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>5_객체 탐색</title>

    <script src="js/jquery-3.6.0.min.js"></script>


    <style>
        .wrap,
        .wrap * {
            border : 1px solid lightgray;
            display: block;
            padding : 5px;
            margin: 15px;
            color : gray
        }

        .type{
            width : 500px;
        }
    </style>
</head>
<body>
    <h1>필터링 메소드</h1>
    <p>
        선택자로 지정한 객체를 기준으로 객체 그룹에서 위치를 통해 객체를 선택하는 메소드
    </p>

    <h4 class="test">test-1</h4>
    <h4 class="test">test-2</h4>
    <h4 class="test">test-3</h4>
    <h4 class="test">test-4</h4>
    <h4>test-5</h4>
    <h4 class="test">test-6</h4>

    <script>
        $(document).ready(function(){
            // filter : 특정 기준과 일치하는 요소를 반환
            // test 클래스 요소 중 짝수 인덱스 선택
            $(".test").filter(":even").css({background:"tomato", color:"white"});
            // 답 : 0, 2, 4번 인덱스가 색 변경됨

            // 함수를 매개변수로 하는 filter 메소드
            // index : 필터링 되기 전 인덱스 값
            $(".test").filter(function(index){
                return index % 2 == 1;
                // 의미 : 리턴 결과가 true인 요소만 남음
            }).css({background:'green', color:'white'});

            // 선택된 요소 중 제일 처음에 있는 요소
            $("h4").first().css("font-size", "1.5em");

            // 선택된 요소 중 제일 마지막에 있는 요소
            // *text : 해당 요소의 텍스트 노드 값
            $("h4").last().text($("h4").last().text() + " : 마지막 요소");
            // 의미 : 괄호 안에 넣은 것은 test-6값 + " : 마지막 요소"

            // 인덱스 번호와 일치하는 요소
            $("h4").eq(3).text($("h4").eq(3).text() + " : eq(3) 메소드로 필터링 됨");

            // 인자 값과 일치하지 않는 요소만 리턴
            $("h4").not(".test").css({background : "pink", color : "white"});
            // 의미 : test 클래스를 인자로 갖지 않는 값 선택
        });
    </script>


    <h1>순회(탐색) 메소드</h1>
    <h3>
        조상 메소드 : 선택된 요소의 상위 요소들을 선택할 수 있는 메소드
    </h3>


    <pre>
        $('selector').parent()
        -선택된 요소의 바로 위 상위 요소

        $('selector').parents([매개변수])
        -선택된 요소의 모든 상위 요소 리턴
        -매개변수가 있으면 매개변수와 일치하는 부모만 리턴

        $('selector').parentsUntil(매개변수)
        -선택된 요소부터 매개변수 요소까지 범위의 요소 리턴
    </pre>

    <div class="wrap test1">
        <div class = "type">div (great-grandparent)
            <ul>ul (grand parent)
                <li>li(direct parent)
                    <span>span</span>
                </li>
            </ul>
        </div>
        <div class = "type">div (grand parent)
            <p>p(direct parent)
                <span>span</span>
            </p>
        </div>
    </div>


    <script>
        $(document).ready(function(){
            // parent : 바로 상위 요소 리턴
            $(".test1 span").parent()
            .css({color:"red", border : "2px solid red"});

            // parents : 모든 상위 요소 리턴
            // $(".test1 li").parents().css("color", "blue");
            
            // li 상위 요소 중 div만
            $(".test1 li").parents("div").css("border", "2px dashed magenta");
        });

            // parentsUntil : 상위 요소 중 해당 요소까지
            $(".test1 span").parentsUntil("div")
            .css("background", "lightgray");
    </script>


    <h3>
        자손, 후손 메소드 : 선택된 요소의 하위 요소들을 선택할 수 있는 메소드
    </h3>
    <pre>
        $('selector').children([매개변수])
        -선택된 요소의 모든 자식 객체 리턴
        -매개변수 있으면 매개변수와 일치하는 자식 객체만 리턴

        $('selector').find(매개변수)
        -선택된 요소의 인자와 일치하는 모든 후손 객체 리턴
    </pre>

    <div class="wrap test2">
        <div class = "type">div (great-grandparent)
            <ul>ul (grand parent)
                <li>li(direct parent)
                    <span>span</span>
                </li>
            </ul>
        </div>
        <div class = "type">div (grand parent)
            <p>p(direct parent)
                <span>span</span>
            </p>
        </div>
    </div>

    <script>
        let style1 = {color : 'red', border : '2px solid red'};
        let style2 = {color : 'blue', border : '2px solid blue'};
        let style3 = {color : 'green', border : '2px solid green'};
        let style4 = {color : 'orange', border : '2px solid orange'};
        let style5 = {color : 'pink', border : '2px solid purple'};

        // test2 클래스의 자식 객체들
        $(".test2").children().css(style1);

        // test2 클래스의 자손의 자손 객체들
        $(".test2").children().children().css(style2);

        // test2 클래스의 자손의 자손 중 ul
        $(".test2").children().children("ul").css(style3);

        // find : 후손 중 해당하는 객체 리턴
        $(".test2").find("span").css(style4);
        $(".test2").find("li").css(style5);

    </script>

    <h3>
        형제 메소드 : 같은 레벨에 있는 요소를 선택할 수 있는 메소드
    </h3>

    <pre>
        $('selector').siblings([매개변수])
        -선택된 요소와 같은 레벨에 있는 모든 요소 리턴
        -매개변수가 있다면 같은 레벨에 있는 요소 중 매개변수와 일치하는 모든 요소 리턴

        $('selector').next()
        -선택된 요소의 같은 레벨 중 다음 한개 요소 리턴

        $('selector').nextAll()
        -선택된 요소의 같은 레벨 중 다음 모든 요소 리턴

        $('selector').nextUntil(매개변수)
        -선택된 요소의 같은 레벨 중 매개변수 이전까지의 모든 요소 리턴(뒤로 탐색)

        $('selector').prev()
        -선택된 요소의 같은 레벨 중 이전 한개 요소 리턴

        $('selector').prevAll()
        -선택된 요소의 같은 레벨 중 이전 모든 요소 리턴

        $('selector').prevUntil(매개변수)
        -선택된 요소의 같은 레벨 중 매개변수 이전까지의 모든 요소 리턴(앞으로 탐색)
    </pre>

    <div class="wrap">div (parent)
        <p>p</p>
        <span>span</span>
        <h2>h2</h2>
        <h3>h3</h3>
        <p>p</p>
    </div>

    <script>
        // 모든 형제 요소 리턴
        $(".wrap h2").siblings().css(style1);

        // h2의 형제 중 p 선택
        $(".wrap h2").siblings("p").css(style2);

        // h2의 바로 다음 요소
        $(".wrap h2").next().css(style3);

        // h2 뒤에 있는 모든 형제 요소
        $(".wrap h2").nextAll().css(style4);

        // h2 뒤의 p 이전까지 존재하는 형제 요소
        $(".wrap h2").nextUntil("p").css("font-size", "3em");

        // h2 바로 이전 요소
        $(".wrap h2").prev().css(style5);

        // h2 앞에 있는 모든 형제 요소
        $(".wrap h2").prevAll().css(style4);

        // h2 앞의 p 이전까지 존재하는 형제 요소
        $(".wrap h2").prevUntil("p").css("border", "dotted");
    </script>





    
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>6_객체 조작</title>
    <script src="js/jquery-3.6.0.min.js"></script>

    <style>
        /* 객체 삽입 */
        .added {
            color : palegreen;
        }

        /* 객체 복제 */
        .item {
            width : 100px;
            height : 100px;
            display : inline-block;
            margin : 5px 0px;
            text-align: center;
            line-height: 100px;
            background : yellowgreen;
        }

        .item span{
            font-size: 24px;
            font-weight: bold;
            color: white;
        }

        .lime{
            background: lime;
        }

        /* 객체 제거 */
        .box {
            width : 100px;
            height : 100px;
            padding : 5px 10px 15px 10px;
            margin :10px;
        }

        #remove-test{
            border : 2px solid red;
        }

        #result{
            border : 2px dashed blue;
        }


        .highlight_0 {background: red;}
        .highlight_1 {background: orange;}
        .highlight_2 {background: yellow;}
        .highlight_3 {background: green;}
        .highlight_4 {background: blue;}

    </style>
</head>
<body>
    <h1>content 관련 메소드</h1>
    <h3>html 메소드</h3>
    <p>
        선택 된 영역의 content 영역을 리턴하거나 설정하는 메소드<br>
        getter로 사용 시 해당 요소를 태그까지 포함하여 얻어오고
        setter로 사용 시 작성 된 html 태그를 실제 태그로 인식 시킴
    </p>
    <h1 id="test1"><a>네이버로 이동</a></h1>
    <h1 id="test2"></h1>
    <script>
        let tmp = $("#test1").html();
        console.log("html 메소드 리턴 값 : "+tmp);

        $("#test2").html(tmp);
        $("#test2").children("a").attr("href","https://www.naver.com");
    </script>

    <hr>

    <div class="testClass1">1번 div</div>
    <div class="testClass1">2번 div</div>
    <div class="testClass1">3번 div</div>

    <script>
        // html, text, val 메소드에는 콜백 함수도 함께 제공
        // 콜백 함수에는 선택 된 요소 목록의 현재 요소 인덱스와
        // 이전 값이라는 두 매개변수가 있으면
        // 함수에서는 새값으로 사용할 문자열을 반환함
        $(".testClass1").html(function(index, html){
            return "<h1>이전 값 : " +html +", 인덱스 : "+index+"</h1>"
        });
    </script>

    <hr>

    <h3>text 메소드</h3>
    <p>
        선택 된 요소의 content 영역을 리턴하거나 설정하는 메소드<br>
        getter로 사용 시 태그는 무시하고,
        setter로 사용 시 html 태그를 문자 자체로 인식함
    </p>
    <h1 id="test3"><a>구글로 이동</a></h1>
    <h1 id="test4"></h1>
    <script>
        let tmp2 = $("#test3").text();
        console.log("text 리턴 값 "+tmp2);

        $("#test4").text("<a>구글로 이동</a>")
    </script>

    <hr>

    <div class="testClass2">1번 div</div>
    <div class="testClass2">2번 div</div>
    <div class="testClass2">3번 div</div>

    <script>
        $(".testClass2").text(function(index, text){
            return "<h1>이전 값 : "+text+", 인덱스 : "+index+"</h1>";
        });
    </script>

    <hr>

    <h1>객체 생성 및 제거</h1>
    <h3>삽입 메소드 part1</h3>
    <pre>
    선택자 요소를 기준으로 매개변수에 작성 된 요소 또는 함수의 리턴 값을 추가

    $(A).append(B) : A 요소 내 뒷 부분에 B 요소를 추가 (자식)
    $(A).prepend(B) : A 요소 내 앞 부분에 B 요소를 추가 (자식)
    $(A).after(B) : A 요소 뒷 부분에 B 요소를 추가 (형제)
    $(A).before(B) : A요소 앞 부분에 B 요소를 추가 (형제)
    </pre>

    <h1 id="add1"><span>A</span></h1>
    <h1 id="add2"><span>A</span></h1>
    <h1 id="add3"><span>A</span></h1>
    <hr>
    <h1 id="add4"><span>A</span></h1>

    <script>
        $(document).ready(function(){
            // setInterval을 사용하여 1초마다 다음 문자 삽입
            let arr = ['B','C','D','E'];
            let index = 0;

            let timer = setInterval(function(){
                let html = "<span class='added'>"+arr[index++] +"</span>";
                $("#add1").append(html);
                $("#add2").prepend(html);
                $("#add3").after(html);
                $("#add4").before(html);

                if(index>3) clearInterval(timer);
            },1000); // 1000 = 1초

        });
    </script>

    <hr>

    <h3>삽입 메소드 part2</h3>
    <pre>
    생성된 요소를 매개변수로 지정한 선택자 요소에 추가
    (part1의 메소드와 선택자, 생성 구문의 순서가 반대)

    $(B).appendTo(A) : B 요소를 A 요소 내 뒷 부분에 추가 (자식)
    $(B).prependTo(A) : B 요소를 A 요소 내 앞 부분에 추가 (자식)
    $(B).insertAfter(A) : B 요소를 A 요소 내 뒷 부분에 추가 (형제)
    $(B).insertBefore(A) : B 요소를 A 요소 앞 부분에 추가 (형제)
    </pre>

    <h1 id="add5"><span>A</span></h1>
    <h1 id="add6"><span>A</span></h1>
    <h1 id="add7"><span>A</span></h1>
    <hr>
    <h1 id="add8"><span>A</span></h1>


    <script>
        $(document).ready(function(){
            let arr = ['B', 'C', 'D', 'E'];
            let index = 0;

            let timer = setInterval(function(){
                let html = "<span class='added'>"+arr[index++] +"</span>";
                $(html).appendTo("#add5");
                $(html).prependTo("#add6");
                $(html).insertAfter("#add7");
                $(html).insertBefore("#add8");

                if(index > 3) clearInterval(timer);
            },1000); // 1000 = 1초
        })
    </script>

    <h3>객체 복제 메소드</h3>
    <p>
        clone([true|false]) : html 요소를 복사하는 메소드<br>
        매개변수로 이벤트 복사 여부 지정(기본 값 : false)
    </p>

    <button id = "clone">clone</button>
    <div id = "clone-test">
        <div id="item1" class="item"><span>안녕</span></div>
    </div>

    <script>
        $(function(){
            // 마우스 오버 이벤트 추가
            $("#item1").hover(function(){ 
            // 마우스가 올라갔을 때
            $(this).addClass('lime');
        }, function(){
            // 마우스가 내려갔을 때
            $(this).removeClass('lime');
        });

        // 버튼 클릭 이벤트
        $("#clone").click(function(){
            // clone 메소드는 기본적으로 이벤트 복사 하지 않음
            // $("#item1").clone().appendTo("#clone-test");

            // true값을 전달하면서 복제하면 이벤트까지 복사
            $("#item1").clone(true).appendTo("#clone-test");
        });


    });
    </script>


    <hr>

    <h3>객체 제거 메소드</h3>
    <p>
        empty : 모든 자식 요소 제거<br>
        remove : DOM 요소 잘라내기. 연관된 이벤트도 모두 삭제<br>
        detach : DOM 요소 잘라내기. 연관된 이벤트 모두 보관
    </p>
    <button id="empty">empty</button>
    <button id="remove">remove</button>
    <button id="detach">detach</button>
    <div id="remove-test" class="box">
        <div id="item2" class="item"><span>안녕</span></div>
    </div>
    <div id="result" class="box"></div>

    <script>
        $(function(){
            // item에 hover 이벤트 추가
            $("#item2").hover(function(){
                $(this).addClass('lime');
            }, function(){
                $(this).removeClass('lime');
            });

            $("#empty").click(function(){
                $("#remove-test").empty();
            });

            $("#remove").click(function(){
                let elem = $("#item2").remove();
                $("#result").html(elem);
            });

            $("#detach").click(function(){
                let elem = $("#item2").detach();
                $("#result").html(elem);
            });

        });
    </script>

    <hr>

    <h1>메소드</h1>
    <h3>each 메소드</h3>
    <p>
        객체나 배열을 관리하는 for in 문과 비슷한 메소드로
        객체나 배열의 요소를 검사함
    </p>

    <p>
        1. $each(object, function(index, item){}) 의 형식으로 사용<br>
        index : 배열의 인덱스 또는 객체의 키<br>
        item : 해당 인덱스나 키를 가진 값<br><br>

        2. $('selector').each(function(index, item){})의 형식으로 사용
    </p>

    <div id = "area1"></div>
    <script>
        $(document).ready(function(){
            let arr = [{name:'네이버', link:'https://www.naver.com'},
                       {name:'구글', link:'https://www.google.com'},
                       {name:'w3school', link:'https://www.w3schools.com'}];

            let html = '';
            $.each(arr, function(index, item){
                html += "<h2><a href='" + item.link + "'>" + item.name + "</a></h2>";
            });
            $("#area1").html(html);
        });
    </script>


    <hr>

    <div id = "wrap">
        <h1>item-0</h1>
        <h1>item-1</h1>
        <h1>item-2</h1>
        <h1>item-3</h1>
        <h1>item-4</h1>
    </div>

    <script>
        $(function(){
            $("#wrap").children().each(function(index, item){
                $(this).addClass("highlight_" + index);
            });
        });
    </script>

    <h3>문서 객체의 특징 판별 : is</h3>
    <p>
        매개변수로 선택자를 입력하고, 선택한 객체가 선택자와 일치하는지 판단하여
        boolean 리턴
    </p>

    <h3 class="test">test1</h3>
    <h3>test2</h3>
    <h3 class="test">test3</h3>
    <h3 class="test">test4</h3>
    <h3>test5</h3>
    <h3 class="test">test6</h3>

    <script>
        $(function(){
            // h3 태그에 차례대로 접근하여 class 속성이 test일 경우 css 변경
            $("h3").each(function(){
                if($(this).is(".test"))
                $(this).css({background:"orangered", color : "white"});
        });
        });
    </script>

    <hr>
    
    <h3>$.noConflict</h3>
    <pre>
        많은 자바스크립트 라이브러리가 '$' 기호를 함수, 변수로 사용하고 있기 때문에
        jQuery 라이브러리와 충돌하는 경우가 종종 있음
        이를 방지하기 위해 noConflict 메소드를 통해 '$' 대신 새로운 alias(별칭)을 부여함
        또, 다른 버전의 jQuery와 충돌 방지를 위해서도 ㅎ사용함
    </pre>

    <h1 id="ncTest">noConflict 테스트</h1>
    <script>
        $(document).ready(function(){
            $("#ncTest").css("color", "red");
        });

        // 이제 이 문서에서 jQuery를 나타내던 '$'는 사용할 수 없고
        // '$' 대신 jq를 사용해야 함
        // let jq = $.noConflict();

        // jq(function(){
        //     jq("#ncTest").css("color", "red");
        // });
    </script>

</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>7_이벤트</title>
    <script src="js/jquery-3.6.0.min.js"></script>

    <style>
        .trg{
            width : 100px;
            height : 100px;
            background: orangered;
            text-align: center;
            vertical-align: middle;
            cursor:pointer;
        }

        .increment{
            background: black;
            width:100px;
            height: 25px;
            color : white;
            margin-top: 20px;
            cursor: pointer;
            text-align: center;
        }
    </style>
</head>
<body>
    
    <h1>이벤트</h1>
    <h3>이벤트 관련 속성</h3>
    <p>
        이벤트 핸들러의 매개변수로 event 객체 전달함<br>
        인라인 방식으로 이벤트 설정시 매개변수 키워드는 event로 고정
    </p>
    <button onclick="test1(event);">실행확인</button>
    <!-- 무조건 event 키워드 고정해야 함 -->

    <script>
        function test1(e){
        console.log(e);
        // 답 : PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
        console.log(e.target);
        // 답 : <button onclick="test1(event);">실행확인</button>
    };
    </script>

    <h3>이벤트 연결 종류</h3>
    <p>
        요소 객체에 이벤트 발생시 연결될 이벤트 핸들러에 지정하는 메소드<br>
        
        $('selector').bind() : 현재 존재하는 문서 객체만 이벤트 연결<br>
        $('selector').unbind() : bind로 연결된 이벤트 제거
    </p>

    <p>
        bind, unbind 메소드는 jQuery 3.0부터 deprecated로 설정되어 대신
        on, off 메소드를 사용함<br>
        $('selector').on('이벤트명', '이벤트 핸들러') : bind 대신 사용<br>
        $('selector').off('이벤트명', '이벤트 핸들러') : inbind 대신 사용<br>
        *on 생성, off 제거라는 뜻
    </p>

    <h1 id="test1">마우스를 올려보세요</h1>

    <script>
        $("#test1").on('click', function(){
            console.log(event.target);
            // 답 : <h1 id="test1">마우스를 올려보세요</h1>
            console.log($(this).text());
            // 답 : 마우스를 올려보세요
        });    

        // 여러 이벤트를 객체로 전달하여 등록
        $("#test1").on({'mouseenter' : function(){
            $(this).css("background", "yellowgreen").text('마우스 올라감');
        }, 'mouseleave' : function(){
            $(this).css("background", "yellow").text("마우스 내려감");
        }, 'click' : function(){
            $(this).off('mouseenter').off('mouseleave')
            .css("background", "orangered").text("이벤트 제거됨");
        }});
    </script>

    <hr>

    <h3>$('selector').on(events, seletor, handler)</h3>
    <pre>
        선택자를 기준으로 매개변수로 전달된 selector에 지정한 이벤트 발생시
        해당 핸들러를 동적으로 적용시켜 이벤트 처리를 할 수 있음
    </pre>

    <div id="wrap">
        <h2>클릭시 h2 요소 추가</h2>
    </div>

    <script>
        // $("h2").on("click", add);
        
        $(document).on('click', 'h2', add);
        function add(){
            $("#wrap").append("<h2>클릭으로 인해 추가됨</h2>")
        }
    </script>

    <h3>one 메소드</h3>
    <p>
        이벤트를 한번만 연결할 때 사용한다
    </p>
    <h1 id = "test2">클릭하세요</h1>
    <script>
        $("#test2").one('click', function(){
            alert('처음이자 마지막 이벤트 발생!');
        });
    </script>


    <h3>trigger 메소드</h3>
    <p>
        특정 이벤트나 기본 이벤트를 강제로 발생시키는 메소드로 사용자 정의 이벤트 발생시 사용<br>
        이벤트 발생시 인자 값 전달 가능
    </p>

    <div class ="trg" id="trg">
        click Num : <span id = "cnt">0</span>
    </div>

    <div class="increment" id="increment">click me!</div>

    <script>
        let cnt = 0;
        $("#trg").on('click', function(){
            cnt++;
            $("#cnt").text(cnt);
        });

        $(".increment").on("click", function(){
            // #trg의 click 이벤트 핸들러를 요청함
            $("#trg").trigger('click');
        });
    </script>

    <p>
        trigger 메소드는 실제 클릭이 일어나는 것이 아니라
        click 이벤트 핸들러를 호출하는 것<br>
        따라서 아래와 같은 경우 a태그의 링크로 실제 이동하지 않음
    </p>

    <a href="https://www.naver.com" id="goNaver"
    onclick="justClicked();">네이버로 이동</a>
    <button id ="btnTrg">trigger를 통한 a태그 클릭</button>
    <script>
        function justClicked(){
            console.log('just clicked!!!');
            // 답 : just clicked!!!
            // 콘솔에서는 이것만 확인 가능
        }
        $('#btnTrg').on('click',function(){
            $("#goNaver").trigger('click');
        });
    </script>

</body>
</html>