본문 바로가기
Front-end/JQuery

[jQuery] 제이쿼리 기초 : 조작하기, 이벤트, 이펙트

by 꼬바리 2021. 4. 27.

#4 jQuery 조작하기


$(document).ready(function () {
            var p = document.getElementsByTagName("p");
//            alert(p.length + ", " +  p.size());
            p[0].style.color = "red";    // javascript
            p[1].style.color = "blue";
            p[2].style.color = "green";
​
            $("p").eq(1).css("color", "aqua");    // jQuery
//            alert($("p").index($(".kbs")));
            $("p").eq($("p").index($(".kbs"))).css("color", "yellow");
​
            //$("요소~요소2") : 요소2를 요소 1에서부터 검색
            var arr = $("h1~p");
//            alert(arr.size());
​
            var result = "";
            for(var i = 0; i < arr.length; i++) {
                //result += arr[i].innerHTML + ", ";    //js
                //result += arr[i].innerText + ", ";
                //result += $(arr[i]).html() + ", ";    //jq
                result += $(arr[i]).text() + ", ";    //jq
            }
//            alert("result : " + result);
            console.log("result : " + result);
​
            var arr2 = $("p:not(.kbs)");    // 제외
//            alert(arr2.size());
​
            // 실행 중에 요소 추가
            //$("b").prepend("<h2>요소 추가(기존요소 앞)</h2>");
            $("<h2>요소 추가(기존요소 앞)</h2>").prependTo("b");
            $("b").append("<h2>요소 추가(기존요소 뒤)</h2>");
            //$("<h2>요소 추가(기존요소 앞)</h2>").appendTo("b");
​
            // 반복
            var arr3 = "";
            $("li").each(function () {
                //arr3 += $(this).html() + " ";
                arr3 += $(this).text() + " ";
            });
//            alert(arr3);
            console.log(arr3);
    
            // 선택요소 감싸기
            $("#message").wrap("<h2/>");    
        });
  1. html(), text(), val()html()과 text() 메서드는 자바스크립트의 innerHTML, innerText와 같이 동작합니다.처음으로 일치하는 요소의 내용을 리턴하며, 파라미터를 전달해줄 경우 해당 값으로 자식에 내용 값을 치환합니다.val은 value 속성을 가져올 수 있으며, 파라미터를 전달해서 변경할 수 있습니다.
  2. prepend(), append(), appendTo(), prependTo()append(내용)은 대상이 되는 요소를 자식요소로 추가합니다. (text 속성 값이 있을 경우 text 속성 값 뒤에 해당하는 요소)appendTo(표현식)은 append()와 차이가 없으나 작성하는 순서가 반대입니다. 이를 사용하면 실행 중에 요소를 추가(DOM)기술을 쉽게 사용할 수 있습니다.prepend와 append의 차이는 대상이 되는 요소를 기존 요소의 앞에 추가할 지, 뒤에 추가할 지의 차이입니다.
  3. each(func)each는 선택자를 통해 선택한 요소가 배열로 들어올 때 각각의 요소를 반복을 통하여 선택할 수 있게 해줍니다. 선택된 요소는 $(this)로 사용하면 됩니다.
  4. wrap()wrap은 선택된 요소를 대상이 되는 태그로 감싸주는 메서드입니다.
  5. find(선택자)find() 메서드는 선택된 요소의 하위 요소 중 대상이 되는 요소를 찾습니다. 파라미터로는 선택자를 전달합니다.
  6. css("속성명", "값")css를 변경해주는 메서드입니다. 속성값을 변경할 수 있습니다.
  7. addClass(클래스명), removeClass(클래스명)해당 요소를 클래스에 추가, 삭제해줍니다.
  8.  

#5 jQuery 이벤트 핸들링

// event
            $("input").focus(function () {    // 포커스를 가졌을 때
                $(this).addClass("myFocused");
            });
            $("input").blur(function () {    // 포커스를 잃었을 때
                $(this).removeClass("myFocused");
            });
​
            //$("#frm").submit(function (event) {
            $("#frm").on("submit", function(){
                event.preventDefault();    // 기본 이벤트 기능 해제
                // 다른 기능으로 대체
                var new_ele = "<li>" + $("#data").val() + "</li>";
                $("#uldisp").append(new_ele);
            });
​
            $("a").click(function (event) {
                event.preventDefault();
                alert("다른 기능으로 사용 가능");
            });
            $("td").click(function () {    // 권장
                alert($(this).text());
            });
​
            $("#good").dblclick(function () {
                alert($(this).text());
            });
​
            $("#txtA").keydown(function (event) {    // 키보드를 누르면 발생
                $("#txtB").val(event.keyCode);
            });
​
            // bind 메소드 연습
            //$("#btn").click(function (event) {
            $("#btn").bind("click", function (){    // 객체와 이벤트를 연결 (addEventListener와 비슷)
                console.log(event);
                alert("버튼 이벤트 처리");
                $("#btn").unbind("click");    // 객체와 이벤트 연결 해제
            });
​
            var count = 0;
            //$("#myArea").bind("mouseenter mouseleave", function (event) {
            $("#myArea").on("mouseenter mouseleave", function (event) {    // on도 가능 (권장)
                count++;
                $("#mResult").text(count + "번 수행");
                if(event.type === "mouseenter") {
                    $("#mResult").css("background", "red");
                } else if (event.type === "mouseleave") {
                    $("#mResult").css("background", "blue");
                }
            });
​
            //live event
            /*$("#btnAdd").click(function () {
                $("ul").append("<li>item" + $("li").length + "</li>");
            });*/
​
            $("#btnAdd").on("click", function () {
                $("ul").append("<li>item" + $("li").length + "</li>");
            });
​
            /*
            $("li").click(function () {
                alert($(this).text());
            });
            */
​
            $(document).on("click", "li", function () {
                alert($(this).text());
            })
​
            $("#btnDie").on("click", function () {
                $(document).off("click", "li");
            })

제이쿼리의 이벤트핸들링 레퍼런스 제이쿼리는 각각의 이벤트에 개별적으로 메서드를 만들어 두었습니다. 이를 통해서 간편하게 이벤트를 관리하는 것이 가능합니다. 또, on()과 bind()같은 메서드를 통해서 요소에 이벤트 핸들러를 추가할 수 있습니다. on이나 bind를 사용하면 여러 이벤트를 나열하여 한번에 핸들링 할 수도 있습니다. 최근에는 bind 보다는 on을 권장하고 있습니다. (3.0 version deprecated)


#6 jQuery Effects

$(document).ready(function(){
    var speech = $("div.speech");
    var defaultSize = speech.css("fontSize");    // 폰트 크기 얻기
    $("#switcher button").click(function () {
        var fnum = parseFloat(speech.css("fontSize"));    // 단위를 제거하고 숫자만
​
        switch (this.id) {    // 현재 이벤트가 발생된 버튼
            case "sw-default":
                fnum = parseFloat(defaultSize);
                break;
            case "sw-large":
                fnum += 8; //fnum *= 1.4 처럼 비율로 줄 수도 있음
                break;
            case "sw-small":
                fnum -= 8;
                break;
        }
        speech.animate({fontSize:fnum + 'px'}, 'fast');    // 숫자는 작을수록 빠름, 'slow', 'fast'
    });
​
    $("#switcher button, a.more").hover(
        // hover는 기본적으로 이벤트 핸들러가 2개 (핸들러1, 핸들러2)
        function (){
            $(this).addClass("myhover");
        },
        function () {
            $(this).removeClass("myhover");
        }
    );
​
    // 문서의 일부 show & hide
    var firstPara = $("p:eq(1)");
    firstPara.hide();
​
    $("a.more").on("click", function () {
        if(firstPara.is(":hidden")) {
            // firstPara.show();
            // firstPara.fadeIn("slow");    // fade 효과
            firstPara.slideToggle("fast");    // slide 효과
            $(this).text("read less");
        } else {
            // firstPara.hide();
            // firstPara.fadeOut("slow");
            firstPara.slideToggle("slow");
            $(this).text("read more");
        }
    })
});

제이쿼리 이펙트 레퍼런스

  1. hide(), show()선택된 엘리먼트를 숨겨주거나 보여줍니다. 이를 사용하면 문서 내의 요소들을 동적으로 감췄다가 나타낼 수 있습니다.
  2. fadeIn(), fadeOut(), fadeToggle()선택된 엘리먼트에 fade 효과를 줍니다. 정수 값을 인자로 넘겨줄 수도 있고, "slow"나 "fast"를 줄 수 있습니다. 정수 값을 줄 경우 숫자가 낮을수록 빠릅니다.
  3. slideUp(), slideDown(), slideToggle()슬라이드 효과를 줍니다. 사용법은 위의 페이드 효과와 동일합니다.

출처 :kyun2.tistory.com/53?category=739343

728x90
반응형

댓글