✿∘˚˳°∘°

48일차 : 객체조작 본문

국비수업/jQuery

48일차 : 객체조작

_HYE_ 2023. 2. 3. 18:15

20230203

1. 객체조작

- css

    <style>
        #test11{
            color: blue;
        }
        .bg-yellow{
            background-color: yellow;
        }
        .t-red{
            color: red;
        }
        #test4{
            overflow: hidden;
        }
        #test4>div{
            width: 100px;
            height: 100px;
            float: left;
        }
        .d3{
            background-color: blue;
        }
        .d4{
            background-color: red;
        }
    </style>

1 - 1 ) each(), is()

   <h3>1. each(), is()</h3>
    <p>each() : 배열을 관리하는 함수로, 선택된 객체들을 모두 순회</p>
    <p>is("선택자") : 선택된 요소에 매개변수로 전달된 속성이 있는지 확인하여 true/false 리턴</p>
    <div id="test1">
        <div class="d1">test-1</div>
        <div class="d2">test-2</div>
        <div class="d1">test-3</div>
        <div class="d2">test-4</div>
        <div class="d3">test-5</div>
    </div>
    <button onclick="func1();">each/is 테스트</button>
function func1(){
    const divs = $("#test1>div");
    /*
    for(let i=0; i<divs.length; i++){
        console.log(divs.eq(i).text());
    }
    divs.forEach(function(item, index){
        item : 배열에 들어있는 요소 divs[0]
        index : for문의 순번 - i
    });
    */
    //each() 사용법1
    //javascript의 매개변수와 순서가 반대이다
    //(주의, javascript에서는 순번이 필요없으면 생략가능 하지만 jQuery는 인덱스번호변수도 반드시 넣어줘야함)
    //첫번째가 번호 두번째가 해당아이템
    divs.each(function(index, item){
        //index : 순회번호 - for문의 i역할
        //item : 해당순번의 객체(배열내부의 값)
        //item은 javascript객체 -> $(item)을 통해서 jQuery객체로 변환해야 jQuery에서 사용가능
        console.log($(item).text()); //그냥 item으로하면 javascript객체이기때문에 innerText로 확인해야함 
        //is()
        if($(item).is(".d1")){
            //만약 item dom객체가 d1이라는 객체를 가지고 있으면 true / 없으면 false
            console.log("d1클래스를 가지고 있는 경우");
            $(item).css("color", "red");
        }else if($(item).is(".d2")){
            console.log("d2클래스를 가지고 있는 경우")
            $(item).css("color", "blue");
        }else{
            $(item).css("color", "green");
        }
    });
    /*
    //each() 사용법2
    $.each(divs, function(index, item){
        console.log($(item).text());
        if($(item).is(".d1")){
            console.log("d1클래스를 가지고 있는 경우");
            $(item).css("color", "red");
        }else if($(item).is(".d2")){
            console.log("d2클래스를 가지고 있는 경우")
            $(item).css("color", "blue");
        }else{
            $(item).css("color", "green");
        }
    });
    */

 

1 - 2 ) addClass, removeClass, hasClass, toggleClass

    <h3>2. addClass, removeClass, hasClass, toggleClass</h3>
    <p>addClass : 클래스를 추가할 때 사용</p>
    <p>removeClass : 클래스 삭제할 때 사용</p>
    <p>hasClass : 클래스를 가지고 있는지 확인할 때(is랑 비슷)</p>
    <p>toggleClass : 클래스가 없으면 추가/있으면 삭제</p>
    <div id="test2">
        <div id="test11">test-1</div>
        <div class="bg-yellow">test-2</div>
        <div>test-3</div>
        <div>test-4</div>
        <div>test-5</div>
    </div>
    <button onclick="func2();">addClass</button>
    <button onclick="func3();">removeClass</button>
    <button onclick="func4();">hasClass</button>
    <button onclick="func5();">toggleClass</button>
//addClass
function func2(){
    const divs = $("#test2>div");
    divs.eq(1).addClass("t-red");
    divs.first().addClass("t-red");//실행되지 않는 이유 : 우선순위가 클래스보다 아이디가 더 높으므로
    divs.eq(3).addClass("t-red").addClass("bg-yellow");
    divs.last().addClass("t-red bg-yellow");//띄어쓰기도 OK
}

//removeClass
function func3(){
    const divs = $("#test2").children();
    divs.eq(1).removeClass("t-red");
    divs.eq(3).removeClass("t-red").removeClass("bg-yellow");
    divs.last().removeClass("t-red bg-yellow");
}

//hasClass
function func4(){
    const divs = $("#test2>div");
    console.log(divs.eq(1).hasClass("t-red"));
    if(divs.eq(1).hasClass("t-red")){
        divs.eq(1).removeClass("t-red");
    }else{
        divs.eq(1).addClass("t-red");
    }
}

function func5(){
    const divs = $("#test2>div");
    divs.eq(2).toggleClass("t-red");
}

 

1 - 3 ) attr, removeAttr, prop

    <h3>3. attr, removeAttr : 엘리먼트 속성 값을 확인, 수정, 삭제하는 함수</h3>
    <h3>prop() : 속성을 컨트롤하는 함수인데 (true/false로 설정하는 속성을 처리하는 함수)</h3>
    <div id="test3">
        <input type="checkbox" name="study" value="java" id="java">
        <label>자바</label>
        <input type="checkbox" name="study" value="oracle" id="oracle">
        <label>오라클</label>
        <input type="checkbox" name="study" value="javascript" id="javascript">
        <label>자바스크립트</label>
        <input type="checkbox" name="study" value="jquery" id="jquery">
        <label>jquery</label>
    </div>
    <button onclick="func6();">attr</button>
    <button onclick="func7();">removeAttr</button>
    <button onclick="func8();">prop</button>
function func6(){
    const label = $("#test3>label");
    label.each(function(index, item){
        //attr("속성명") : 해당 속성에 적용되어있는 값을 읽어옴(확인)
        const id = $(item).prev().attr("id") //라벨기준 직전input의 id가 필요함
        //attr("속성명", 값) : 해당 속성명에 값을 대입(수정)
        $(item).attr("for", id);
    });
}

function func7(){
    const label = $("#test3>label");
    /*
    label.each(function(index, item){
        $(item).removeAttr("for");//removeAttr("속성명") 해당 속성명 삭제
    });
    */
    //취소 일괄적용
    //배열로 읽어온 dom객체에 설정은 한번에 적용가능
    label.removeClass("for");
}

function func8(){
    const input = $("#test3>input");
    input.prop("checked", true);
}

 

1 - 4 ) css()

    <h3>4. css() : 선택된 요소의 css속성값을 가져오거나 설정하는 함수</h3>
    <div id="test4">
        <div class="d3"></div>
        <div class="d4"></div>
    </div>
    <button onclick="func9();">css</button>
function func9(){
    const divs = $("#test4>div");
    //css함수에 매개변수를 1개 작성하면(속성이름만 작성) 해당 속성 값을 가져옴
    console.log(divs.eq(0).css("background-color"));
    console.log(divs.eq(1).css("background-color"));
    //매개변수를 두개 작성하면 해당 css속성을 변경
    divs.eq(1).css("background-color", "green");
    //css속성을 한번에 여러개 변경하는 경우 1
    //divs.eq(0).css("background-color", "yellow").css("float", "none");
    //css속성을 한번에 여러개 변경하는 경우 2
    divs.eq(0).css({
        "background-color" : "yellow", 
        "float" : "none"
    })
}

 

1 - 5 ) html(), text(), val()

    <h3>5. html(), text(), val()</h3>
    <p>html() : 선택된 요소의 컨텐츠영역(innerHTML)을 가져오거나 수정</p>
    <p>text() : 선택된 요소의 컨텐츠영역(innerText)을 가져오거나 수정 / 단, 내부내용 중 태그는 가져올 수 없음</p>
    <p>val() : 선택된 요소의 value를 가져오거나 수정</p>
    <div id="test5">
        <h1><p>안녕!</p></h1>
        <input type="text" name="str">
    </div>
    <button id="btn1">html</button>
    <button id="btn2">text</button>
    <button id="btn3">val</button>
const btn1 = $("#btn1");
btn1.click(function(){
    const h1 = $("#test5>h1");
    console.log(h1.html());
    h1.html("<p>변경</p>"); //라인이 조금 올라오는이유 : <p>태그가사라지므로 <h1>안녕<h1>이 된다
});

$("#btn2").click(function(){
    const h1 = $("#test5>h1");
    console.log(h1.text());
    h1.text("<p>변경</p>");
});

$("#btn3").click(function(){
    const input = $("#test5>input");
    console.log(input.val()); //현재 입력값을 읽어옴
    input.val("변경값");
});

 

1 - 6 ) append, prepend, after, before

    <h3>6. append, prepend, after, before : 생성한 문서객체를 특정위치에 삽입하는 함수</h3>
    <p> 동일한 기능을 가진 appendTo, prependTo, insertAfter, insertBefore</p>
    <div id="test6">
        <p>test-1</p>
        <p>test-2</p>
        <p>test-3</p>
        <p>test-4</p>
    </div>
    <button id="btn4">append</button>
    <button id="btn5">prepend</button>
    <button id="btn6">after</button>
    <button id="btn7">before</button>
$("#btn4").click(function(){
    //p태그 만들고 안데 test라는 문자를 넣는 방법  js
    //const p = document.createElement("p");
    //p.innerText = "test";
    //p태그 만들고 안데 test라는 문자를 넣는 방법  jq
    //const p = $("<p>test</p>"); 
    const p = $("<p>");
    p.text("test");
    //객체1.append(객체2) : 객체1의 마지막 자식으로 객체2를 추가
    const div = $("#test6");
    //div(객체1)의 마지막 자식으로 p(객체2)추가
    div.append(p);
    //p.appendTo(div); 위와동일
});

$("#btn5").click(function(){
    const p = $("<p>tset</p>");
    //객체1.prepend(객체2) : 객체1의 첫번째 자식으로 객체2를 추가
    $("#test6").prepend(p);
    //p.prependTo($("#test6"));
});

$("#btn6").click(function(){
    const p = $("<p>after-test</p>");
    //객체1.after(객체2) : 객체1의 바로 다음요소로 객체2 추가(자식XXX다음요소OOO)
    $("#test6").after(p);
    //p.insertAfter($("#test6"));
});

$("#btn7").click(function(){
    const p = $("<p>");
    p.append("before-test");//<p>before-test</p>
    //객체1.before(객체2) : 객체1의 바로 이전요소로 객체2 추가
    $("#test6").before(p);
    //p.insertBefore($("#test6"));
});

1 - 7 ) remove, empty

    <h3>7. remove, empty : 문서객체를 제거하는 함수 </h3>
    <p>remove : 특정 문서 객체를 제거</p>
    <p>empty : 특정 문서 객체를 비움 -> 후손을 모두 삭제 </p>
    <button id="btn8">remove</button>
    <button id="btn9">empty</button>
$("#btn8").click(function(){
    const div = $("#test6");
    div.children().eq(1).remove(); //두번째자식인 test-2만 지움
});

$("#btn9").click(function(){
    const div = $("#test6");
    div.empty();//자식들(내부)를 모두지우지만 자기자신(div id="test6")은 남아있음
});

 

1 - 8 ) 이동 / 복사

    <h3>8. 문서객체의 이동 및 복사</h3>
    <div id="test7">
        <h2>h2</h2>
        <h3>h3</h3>
    </div>
    <div id="test8"></div>
    <button id="btn10">이동</button>
    <button id="btn11">복사</button>
$("#btn10").click(function(){
    const h2 = $("#test7>h2"); 
    $("#test8").append(h2); //h2객체는 하나이므로 test8의 마지막자식으로 들어가고 test7에서 사라짐
});

$("#btn11").click(function(){
    const h2 = $("#test7>h2").clone(); //원본을 건들이지않고 복제
    $("#test8").append(h2);
});

 

2. 객체조작예제

 

<!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>Document</title>    
    <style>
        #result1,#result2{
            border: 3px solid red;
            width:500px;
            height : 250px;
        }
        
        .title{
            background-color: black;
            color: white;
        }
        .name{
            background-color: blue;
        }
        .age{
            background-color: yellow;
        }
        .addr{
            background-color: gray;
        }
        #exam3  div{
            width: 100px;
            height: 100px;
            border: 1px solid black;
            display: inline-block;
        }
    </style>    
    <script src="js/jquery-3.6.3.min.js"></script>    
</head>
<body>
    <h1>객체조작 실습</h1>
    <hr>
    <h3>1. 다음 테이블에 있는 학생정보를 each를 이용하여 결과창에 출력하세요.</h3>
    <table id="tbl1" border="1">
        <tr>
            <th>이름</th><th>나이</th><th>주소</th>
        </tr>
        <tr>
            <td>홍길동1</td><td>20</td><td>서울</td>
        </tr>
        <tr>
            <td>홍길동2</td><td>30</td><td>경기도</td>
        </tr>
        <tr>
            <td>홍길동3</td><td>40</td><td>서울</td>
        </tr>
    </table>
    <p id="result1"></p>
    <button id="btn1">학생정보 출력</button>
    <hr>
    <h3>2. 적용버튼 클릭 시 스타일이 적용되고 취소버튼클릭 시 스타일적용이 취소되게 하세요.(addClass,removeClass 사용하며 위의 tbl1을 그대로 사용)</h3>
    <button id="btn2">스타일적용</button>
    <button id="btn3">스타일취소</button><br>    
    <hr>
    <h3>3. 다음 2개의 그림 중 선택한 후 복사 될 수 있도록 구현하시오. 초기화버튼누르는경우 초기화</h3>
    <div id="exam3">
        <fieldset>
            <legend>보기</legend>
            <div class="copy" style="background-color: red;"></div>
            <div class="copy" style="background-color: blue;"></div>
        </fieldset>
        <fieldset>
            <legend>복사공간</legend>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </fieldset>
    </div>
    <button id="btn4">초기화</button>
    <hr>
    <h3>4. 다음 테이블에서 체크된 학생 정보만 결과창에 출력하세요.</h3>
    <table id="tbl2" border="1">
        <tr>
            <th>체크</th><th>이름</th><th>나이</th><th>주소</th>
        </tr>
        <tr>
            <th>
                <input type="checkbox">
            </th>
            <td>홍길동1</td><td>20</td><td>서울</td>
        </tr>
        <tr>
            <th>
                <input type="checkbox">
            </th>
            <td>홍길동2</td><td>30</td><td>경기도</td>
        </tr>
        <tr>
            <th>
                <input type="checkbox">
            </th>
            <td>홍길동3</td><td>40</td><td>서울</td>
        </tr>
    </table>
    <p id="result2"></p>
    <button id="btn5">출력</button>
    <script src="js/02_exam2.js"></script>
</body>
</html>
$("#btn1").click(function(){
    const allTd = $("#tbl1 td");
    //하나씩 꺼내서 사용
    // allTd.eq(0) ~ allTd.eq(8)까지 꺼내야함
    /*
    console.log(allTd.eq(0).text());
    console.log(allTd.eq(1).text());
    console.log(allTd.eq(2).text());
    console.log(allTd.eq(3).text());
    console.log(allTd.eq(4).text());
    console.log(allTd.eq(5).text());
    console.log(allTd.eq(6).text());
    console.log(allTd.eq(7).text());
    console.log(allTd.eq(8).text());

    //$("#result1").text(allTd.eq(0).text());
    //text는 누적이 X 계속 바뀌는것
    /*로직
    $("#result1").append(allTd.eq(0).text());
    $("#result1").append("/");
    $("#result1").append(allTd.eq(1).text());
    $("#result1").append("/");
    $("#result1").append(allTd.eq(2).text());
    $("#result1").append("<br>");
    $("#result1").append(allTd.eq(3).text());
    $("#result1").append("/");
    $("#result1").append(allTd.eq(4).text());
    $("#result1").append("/");
    $("#result1").append(allTd.eq(5).text());
    $("#result1").append("<br>");
    $("#result1").append(allTd.eq(6).text());
    $("#result1").append("/");
    $("#result1").append(allTd.eq(7).text());
    $("#result1").append("/");
    $("#result1").append(allTd.eq(8).text());
    $("#result1").append("<br>");
    */
    allTd.each(function(index, item){
        $("#result1").append($(item).text());
        if(index%3 == 0 || index%3 == 1){
            // 0 1 3 4 6 7
            $("#result1").append("/");
        }else{//index%3 == 2
            // 2 5 8
            $("#result1").append("<br>");
        }
    });
});


$("#btn2").click(function(){
    //const title = $("#tbl1 th");
    const tr = $("#tbl1 tr");
    tr.each(function(index, item){
        //첫번째 tr과 두번째세번째네번째 tr의 섹션인 다름
        if(index == 0){
            //첫번째 tr일때 
            $(item).children().addClass("title");
        }else{
            $(item).children().first().addClass("name");
            $(item).children().eq(1).addClass("age");
            $(item).children().last().addClass("addr");
        }
    });
});

$("#btn3").click(function(){
    const th = $("#tbl1 th");
    th.removeClass("title");
    $("#tbl1 tr>td:first-child").removeClass("name");
    $("#tbl1 tr>td:nth-child(2)").removeClass("age");
    $("#tbl1 tr>td:last-child").removeClass("addr");
    
});


/*
//js
const copy = document.querySelector(".copy");
for(let i=0; i<copy.lenght; i++){
    copy[i].onclick = function(){
        const selectColor = this.style.bacgroundColor;
        //copy[0] - this / copy[1] - this
    }
}
*/
let selectColor = "transparent"; //아래코드에서도 사용하기위해 let타입 전역변수로 설정
$(".copy").click(function(){
    //this - copy에 대한 클릭이벤트가 2개가 있는데, 해당하는 고유한 무언가가 필요할 때는 this가 필요
    //즉, 첫번째 div를 클릭하면 이게(이벤트를발생시킨친구) this 두번째 div를 클릭했을 땐 두번째 div가 this
    // this : 이벤트를 한번에 설정한 경우, 해당 이벤트를 발생시킨 요소
    selectColor = $(this).css("background-color");
    console.log(selectColor);
    
});

//$("#exam3>fieldset").last().children("div")
$("#exam3 div:not(.copy)").click(function(){
    //fieldset이 있으면 자손처리X
    $(this).css("background-color", selectColor);
});

$("#btn4").click(function(){
    $("#exam3>fieldset").last().children("div").css("background-color", "transparent");
    selectColor = "transparent";
});

$("#btn5").click(function(){
    /* 방식1 : 방식 1 : tr을 모두 읽어온 후 checkbox에 체크유무를 확인하는 방식
    const tr = $("#tbl2 tr");
    const result2 = $("#result2");
    result2.empty();//초기화를 하지않으면 출력을 누를때마다 중복되어 들어가므로 그걸 없애주기위해
    tr.each(function(index, item){
        if(index != 0){
            //$(item).children().first().children();
            const checkbox = $(item).find("input[type=checkbox]");
            const check = checkbox.is(":checked");
            if(check){
                const td = $(item).children();
                const text = td.eq(1).text()+"/"+td.eq(2).text()+"/"+td.eq(3).text()+"<br>";
                result2.append(text);
            }
        }
    });
    */
   // 방식 2 : 체크된 체크박스를 가지고와서 체크박스 기준으로 처리
    const result2 = $("#result2");
    result2.empty();
    const tr = $("#tbl2 input[type=checkbox]:checked").parent().parent();
    tr.each(function(index, item){
        const td = $(item).children();
        const text = td.eq(1).text()+"/"+td.eq(2).text()+"/"+td.eq(3).text()+"<br>";
        result2.append(text);
    });
});
Comments