카테고리 없음

JQuery 수업

크피르 2022. 12. 28. 16:50

제이쿼리 쓰는 이유

jQuery는 알아서 반복해서 자식의 자식(부모의 부모)을 알아내기 때문에 DOM을 쓰는 것보다 찾기 편함, 그러나 순수 JavaScript 보다 느리다는 단점이 있음.

https://www.nextree.co.kr/p9747/

 

jQuery와 DOM 첫걸음

jQuery는 JavaScript의 뛰어난 라이브러리 중 하나입니다. 순수 JavaScript에 비해 간단하게 DOM접근을 할 수 있다는 것이 큰 이유입니다. DOM이 무엇인지, 이 DOM접근을 하는 경우와 이유는 무엇인지 알아

www.nextree.co.kr

그러나, 최근 바닐라 JS나 TypeScript 등으로 대체되고 있으며, 읽을 줄 아는 선에서만 공부하기로 한다. (ajax때문에도..)

https://velog.io/@sy3783/jQuery1.-%EB%8D%94-%EC%9D%B4%EC%83%81-%EC%A0%9C%EC%9D%B4%EC%BF%BC%EB%A6%AC%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%A7%80-%EC%95%8A%EB%8A%94-%EC%9D%B4%EC%9C%A0

 

jQuery_더는 제이쿼리를 사용하지 않는 이유

한때 유명했던 jQuery가 다양한 라이브러리의 등장으로 이제 거의 쓰이지 않게 되었다. 왜 그럴까?

velog.io


 

제이쿼리 불러오기(head안에 넣는다) -> jQuery cdn 검색 - jQuery 3.x버젼

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

 

https://codingapple.com/unit/js-6-jquery-basic/

 

jQuery 사용법 간단정리 - 코딩애플 온라인 강좌

0:36 jQuery 설치  3:24 여러가지 jQuery 기본 함수 9:38 오늘의 숙제 (모달창 만들기) 오늘의 숙제 :  버튼하나 아무데나 만들고 버튼 누르면 모달창을 띄워오십시오.  모달창 디자인은 로그인하세요

codingapple.com

문법

// $(선택자).매서드(속성명);
// $(선택자).매서드("속성명", "속성값");
// $(선택자).매서드(익명함수/함수명);
// JQuery의 메서드를 통ㅎ 실행한 후에는 JQuery객체가 다시 반환되기 때문에 연속적인 매서드의 
나열이
//

 

 

구조

<!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">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script scr="sample10.js"></script>
    <title>Document</title>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <th>번호</th>
                <th class="title">제목</th>
                <th>작성자</th>
                <th>작성일</th>
                <th class="until">조회수</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>제목입니다.</td>
                <td>tester</td>
                <td>2022-12-28</td>
                <td>1</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td>2</td>
                <td>테스트중입니다.</td>
                <td>admin</td>
                <td>2022-12-28</td>
                <td>2</td>
            </tr>
        </tfoot>
    </table>
</body>
</html>
 

결과 : 


매서드 

$("tbody tr")[0] //<!-- 인덱스를 활용하면 JQuery는 더이상 못씀--> <th>번호<th>는 DOM Element Object로 반환되서 아래 매서드(first, last, filter, not) 사용 불가

$("tbody tr").eq[0]; //인덱스 0번 가져오기 // jQyery Object 로 반환 // jQuery.fn.init [th, pervObject: jQuery,fn,init(15)

 

//선택자로 선택된 목록에서 추가적으로 조건 지정하여 가져오는 매서드들

// .first() , .last() , eq(index) , filter(selector) , not(selector) //selector은 css에서의 선택자들

$("tbody tr").first[0]; 

$("tbody tr").last[0];

$("th,td"); // th,td 가져오기

$("th,td").filter("th"); //th인것만 가져오기

$("th,td").not("th"); //th가 아닌 것만 가져오기

 

//부모

$("td"); //td 목록 jQyery Object로 반환

$("td").parent();  // td의 부모 반환[tr]

$("td").parents(); // td부모의 부모 반환 [tbody]

$("td").parentsUnitl();  // td 상위 부모 다 반환 [tr, td, tbody, table, body, html]

$("td").parentsUnitl("tbody") // [tr, tr]

$("td").parentsUnitl("table") // [tr,tr,tbody]

$("td").parents("table"); // table

$("td").parents("table").children(); //[thead, tbody]

$("table").children(); [thead, tbody]

$("table").children().children(); [tr(thead의 자식),tr,tr(tbody의 자식2개)]

$("table").children().children().children(); [th*5(tr의 자식5개),td*5(tr의 자식,td*5(tr의 자식2개)] //엥???

dom

document,getElementsByTagName("table")[0].children[1]; //[tr]

document,getElementsByTagName("table")[0].children[1].children; //[tr tr]

 

$("table").find("td"); //[td, td, td, td, td, td, td, td, td, td, td, td, td, td, td]

 

// 형제 찾기(동일계층)

$(".title"); //[td.title]

$(".title").next; //[td]

$(".title").prev; //[td]

$(".title").nextAll; //[td, td, td]

$(".title").prevAll; //[td]

$(".title").nestUntil(".until"); //[td,td]

$(".until").prevUnti(.tilte); //[td,td]

$("td"); //[td, td.tilte, td, td, td.until, td, t,d, td, td, td]

$("td").is(.noTilte"); //false

 


 

// 함수

$("td").each(function(index, element) {   // 매개변수 x,y

    console.log(index, element)

});

 

결과 : td태그에 대한 반복

                <td>1</td>
                <td>제목입니다.</td>
                <td>tester</td>
                <td>2022-12-28</td>
                <td>1</td>
                <td>2</td>
                <td>테스트중입니다.</td>
                <td>admin</td>
                <td>2022-12-28</td>
                <td>2</td>

$("td").each(function(index, element) {   // 매개변수 x,y

    element.style.color = "red";

    element.style.backgroundColor = "gray";

});

 

결과 : 

 

// 지정 태그에 클래스, 속성 추가/제거하는 메서드

// .addClass() , .removeClass(), toggleClass() , .css(), .attr(), .removeAttr()

$("td").addClass("class-name");

$("td").removeClass("class-name");

$("td").toggleClass("class-name"); // 엘리먼트(태그)에 클래스 네임이 없으면 넣어주고, 있으면 빼줌(on-off)

 

// 함수로 짝수 번째 태그에 클래스 부여

$("td").addClass(function(index) {   // 매개변수 x,y

    if(index % 2 ===0){

        return "class-name";

});

결과 : [th.class-name, th, th.class-name, th]

 

// 함수로  태그에 클래스 제거

$("td").removeClass(function(index) {   // 매개변수 x,y

    if(index % 2 ===0){

        return "class-name";

});

결과 : [th, th, th, th]

 

// 함수로  태그에 클래스 제거 및 부여

$("td").toggleClass(function(index) {   // 매개변수 x,y

    if(index % 2 ===0){

        return "class-name";

});

결과 : [th.class-name, th.class-name, th.class-name, th.class-name]

 

// 

$("th").attr("style", "color:red");

$("th").attr("style");

<- 'color:red;'

$("th").eq(0).nextAll().attr("style", "color:blue");

$("th").attr("style");

<- 'color:red;'

 

결과 : 

 

//

$("th").attr("style", function(index, value) {   // 매개변수 x,y

    return value + "backgrount-color : gray;";

});

 

//

$("th").attr("style", function(index, value) {   // 매개변수 x,y

    return "font-size: 24px";

});

 

//설정된 속성제거

$("th").removeAttr("style");

 

// css 메서드 사용

$("th").css("color", "red")

 

// css로 rgb 색상 불러오기

$("th").css("color");

<-rgb(0, 0. 0)

 

// 컬러 및 폰트 초기화

$("th").css("color", "");

$("th").css("font-size", "");

 

// 테이블 제목 중 짝수 인덱스만 폰트 크기 변경

$("th").css("font-size", function(index, value) {

    if(index % 2 === 0) {

        return "24px";

    }

});

 

// 

$("th).html(); // '번호'

$("th).text(); // '번호제목작성자작성일조회수'

 

$("thead th").html();??

$("thead th").text();??

 

$("th").html("<a href='#'>링크</a>"); //태그를 html형식으로 추가. 링크걸림

$("th").text("링크"); //태그를 text로 추가. 그냥 text만 쳐짐

 

// 링크 걸기 함수

$("th").html(function(index, value) {

    return <a href='#'>" + value + "</a>";

});

 

// 태그 생성

document.createElement("tr");

<- <tr><tr>

 

$("<tr>");

<- [tr]

 

$("<tr>")[0];

<- <tr><tr>

 

$("<input>")[0];

<- <input>

 

$("<input>").attr("type", "password")[0];

<- input type="password">

 

var input = $("<input>").attr("type", "password").attr("name", "pass"); //태그생성

$("body").append(input);  //body 밑에 붙음

$("body").prepend(input);  //body 위에 붙음

$("body").after(input);  //body 밑에 붙음

$("body").before(input);  //body 위에 붙음

 

// 태그에 태그 추가 후  그 태그에 속성 추가 $("th").append($"<a>").attr("href", "#").text("링크"); //이거 문법 틀림 ㅠ.ㅠ 확인해보기..

$("<th>").append($"a").attr("href", "#").text("링크");

 

// th태그 중 마지막 태그 조회수+링크var a = $("<a>").attr("href", "#").text("링크");$("th").append(function(index){    return a;});

 

//

$("th").append(function(index){

    retrun $("<a>").attr("href", "#").text("링크");

});

 

$("th").append(function(index){

   if(index % 2 === 0) {

        retrun $("<a>").attr("href", "#").text("링크");

    }

});

 

// th뒤에 a 붙이기(추가가 아니라 이동)

var a = $("<a>").attr("href", "#").text("링크");

a.appendTo("th");

<=> $("th").append(a);

<=> a.insertAfter("th");

// th앞에 a 붙이기

a.insertBefore("th");

 

// th앞에 a 붙이기 (추가가 아니라 이동)

// 1개 선택 일 때, 동일태그가 없으면 추가, 동일태그가 있으면 이동

// 2개 이상 선택일 때 추가됨

a.prependTo($("th")[0]);

a.prependTo($("th")[1]);

a.prependTo($("th")[2]);

 

// th 위치 바꾸기 (추가가 아니라 이동)

$("th,td");

$("th,td").after(function(index) {

     if(index % 5 === 2) {

        return $("th, td").eq(index - 1);

    }

});