코딩 기록들

[FrontEnd] jQuery 본문

FrontEnd Programming

[FrontEnd] jQuery

코딩펭귄 2024. 3. 20. 08:58

- Node(Element)를 간편하게 컨트롤하기 위한 라이브러리 (즉, 이벤트를 관리하기 위함)

jQuery는 아래작업들을 편하게 만들어준다
  • HTML 문서에서 Element 찾기
  • HTML Content 변경하기
  • 사용자의 Action 에 반응하기 ex)마우스, 키보드
  • 웹 페이지의 내용을 애니메이션 하기 -> 애니메이션은 css가 더 효율적
  • 네트워크에서 새로운 컨텐츠 받아오기
jQuery로 처리할 수 있는 Element들의기능들

- css, event, animation, create, modify, delete 등을 처리

Network

- 비동기통신을 간편하게 처리함

 

- HTML문서는 DOM(Document Object Model = 노드들의 집합)의 집합

- 모든 브라우저에서 자바스크립트가 동일하게 보일수 있도록 해주는것 -> 크로스 브라우징!!! (jQuery)로 할 수 있다

jQuery

 

 

jQuery 시작하기

https://jquery.com/download/

해당 사이트 들어가서 < Download the compressed, production jQuery 3.7.1 > 우클릭 후 프로젝트 폴더에 저장

/*Rendering이 끝나기 전*/
// document.getElementById(); --> 옛날방식
var h1Element = document.querySelector("h1"); //document : html문서 전체를 의미함. 이 문서에서 h1을 찾아와라!
console.log("Before Render >", h1Element);
// alert("Before Render >" + h1Element.innerText); //innerText : h1에 있는 content의 결과(text)를 전부 가지고 오는것

/*
* 브라우저가 tag를 모두 분석한 뒤 화면에 노출시키는 Rendering과정이 끝나고나면 
* onload이벤트를 호출한다
* Rendering이 끝난 후 부터 DOM을 Handling할수있다
*/

// 아래는 랜더링이 끝나면 함수를 호출하라는 의미
window.onload = function(){ //익명함수 정의
    /*Rendering이 끝난 후*/   
    var h1Element = document.querySelector("h1"); 
    console.log("After Render >", h1Element);
    alert("After Render >" + h1Element.innerText);
};

 

.text("바꿀텍스트") -> text 변경(세팅)하는 방법

$().ready(function(){ //rendering이 끝나면 이 함수를 수행해라 (콜백)
    // Rendering이 끝나면 파라미터로 전달된 함수가 실행된다
    // 단, Rendering이 언제 끝날지는 알 수 없다

    // alert(); 를 실행해서 정상적으로 경고창이 뜨는지를 항상 먼저 확인한다
    // alert("jQuery Loading and Rendering 완료");

    // js: document.querySelector("h1");과 동일
    var h1Element = $("h1");
    console.log(h1Element);

    // js: alert(h1Element.innerText);과 동일
    console.log(h1Element.text());

    //h1 DOM의 내용을 변경
    h1Element.text("where to?");
jQuery 시작하기

  .ready()  

=> rendering이 끝난 후의 이벤트

=> ready()이벤트가 실행되면, html문서를 읽어 dom요소를 모두 객체화 시킴


----- (jquery의).ready ==> (java script의)window.onload와 완전히 동일함 (아래 3가지 표현식 모두 동일한 의미) -----

  • jQuery(document).ready(); //이게 넘 길어서 짧은 표현식으로 써줌 : $==> jquery객체
  • $(document).ready(); // jQuery(document).ready();의 shorthand 표현식
  • $().ready(); // $(document).ready();의 shorthand 표현식

 


셀렉팅

- css의 셀렉터와 jQuery의 셀렉터는 완전하게 동일하다

(단, css의 셀렉터가 전체를 탐색하기 때문에 속도가 훨씬 느림)

좌측 : css셀렉터 / 우측 : jquery셀렉터

셀렉팅 - javascript로 표현하면
window.onload = function(){ //rendering끝나면 아래 실행해라!

    // var liElements = document.querySelector("li"); //처음찾은 li만 가져와라
    var liElements = document.querySelectorAll("li"); //li전부를 가져와라
    console.log(liElements);

    liElements.forEach(function(li) {
        console.log(li.innerText);
        li.innerText="Seoul";
    });

};
셀렉팅 - jquery 로 표현하면
$().ready(function(){
    alert("!");

    var liElements = $("li");
    console.log(liElements);
    console.log(liElements.text());

    liElements.text("Seoul");
});

 

결과

 

여러 엘리먼트 가져오기
$("li"); // li요소를 가져와라​

 

여러 엘리먼트 중 하나만 가져오기(ID Selector)
$("destinations");   //id가 destinations 인 요소를 가져온다

 

여러 엘리먼트 중 특정한 것만 가져오기(Class Selector)
$(".promo"); //class가 promo인 요소를 가져옴​

 

$().ready(function(){
    var destinationsElement = $("#destinations");
    console.log(destinationsElement);

    console.log(destinationsElement.text());
    console.log(destinationsElement.html());
});

.text() : 텍스트 자체를 보여준다

.html() : 내부의 태그들까지 보여준다

 

 

$().ready(function(){
    var destinationsElement = $("#destinations");
    console.log(destinationsElement);

    console.log(destinationsElement.text());
    console.log(destinationsElement.html());

    destinationsElement.html("<li>None</li>");
    // destinationsElement.text("<li>None</li>");
});

html은 괄호 안에 들어있는 태그로 대체되고, 텍스트까지 변경되고,

text는 텍스트자체만 변경해준다.

 

 

하위요소 셀렉팅

id가 destinations 하위의 li 요소찾기 (스페이스로 요소 구분함)

> : 부모요소의 직속 자식요소만 검색함

 

 

다중 요소 셀렉팅

, 는 여러개의 요소를 동시에 검색할 수 있도록 함
$(".promo, #france");

 

 

PSEUDO Classes

처음과 끝
$("#destinations li:first");
$("#destinations li:last");

 


Dom Traversinsg

- traversing은 하위요소 탐색보다 더 많은 코드를 쳐야하지만, 훨씬 빠르게 요소를 찾을 수 있다

$("#destinations li");           //하위요소 탐색
          ↓
$("#destinations").find("li");    //selection & traversal
 $("li:first");       
       ↓
$("li").first();
$("#destinations").children("li");
//cildren은 직속요소만 가져옴 : Css의 > 와 동일

 

 

 


DOM  다루기 (버튼만들기)

JS로 한다면?
window.onload = function() {
    //Element 생성.
    var price = document.createElement("p");
    price.innerText = "$399.99"
    console.log(price);

    //Element 추가
    var package = document.querySelector(".package");
    package.append(price); //package내부에다가 price를 추가
    // package.prepend(price); //젤위로감
    // package.after(price);
    // package.before(price);

    //버튼 제거
    var buttonArea = document.querySelector(".package-button-area");
    buttonArea.remove();
};
jQuery로 한다면?
$().ready(function(){

    //1st: p태그 만들기 (태그안에 들어가는 값이 단순한 경우)
    var price = $("<p>$399.99</p>");
    //p태그 만들기 (태그안에 들어가는 값이 복잡한, 동적인 경우)
    // var price = $("<p></p>")
    // price.text("$399.99");

    //2nd: .package내의 가장아래쪽으로 붙이기
    $(".package").append(price);

    //3rd: .package-button-area 지우기
    $(".package-button-area").remove();
});
요소 추가를 위한 방법들
.append(<element>) -> $('.vacation').append(price); // vacation요소의 안쪽 가장 마지막부분에 요소 추가

.prepend(<element>) -> $('.vacation').prepend(price); // vacation요소의 안쪽 가장 첫부분에 요소 추가

.after(<element>)

.before(<element>) -> $('.vacation').before(price); //vacation 요소 이전에 price요소 추가

 

 

클릭이벤트 만들기
$('button').on('click', function(){
});
// 모든 button객체를 대상으로, 
// click이벤트가 발생하면
// button요소가 클릭되면 function 실행됨

 

클릭'이벤트'는 

$(selector.click(callbackFunction); --> 이 문법이 Deprecated되어버림.)
    $(".package-green-button").click(function() {}

-> 이렇게 사용하지 말고

$(".package-green-button").on("click", function() ){ }

-> 이런식으로 작성해야된다!

 

closest

: 클릭한버튼의 부모들 중에서 class 가 vacation에 가장 가까운 부모를 찾아라

 

Event가 적용되는 대상

- Event 제어의 대상이 되는 객체는 $(document).ready(); 가 호출되기 전에 객체화 된 Element

- jQuery를 통해 동적으로 추가된($(document).ready() 이후 추가된) Element 들에 대해서는 Event를 할당할 수 없게 됨

  • dom <- render을 할 때 생성됨
  • Shadow Dom <- render 이후 생성된 것 ,(브라우저에는 생기지만 실제로 동작은안되는것. jquery로 이벤트를 줄 수 없다. 따라서, element를 생성할 때 이벤트를 줘야한다)
  • virtual Dom <- React가 만들어낸 말(shaow dom과 의미는 동일함)

 

 


 

Mouse Event

$().ready(function(){
    //이미지에 마우스를 올리면 ~ 해라
    $("img")
    .on("mouseenter", function() {;
        // $(".ticket").show(); //하면 숨어있던 티켓이 나옴
        // $(".ticket").slideDown(200);
        $(".ticket").fadeIn();
    })
    .on("mouseleave", function() {;
        // $(".ticket").hide();
        // $(".ticket").slideUp(50);
        $(".ticket").fadeOut();
    })
    .on("click", function() {;
        console.log("이미지를 클릭함");
    })
    .on("Contextmenu", function(event){
        event.preventDefault(); 
        // preventDefault(); : 오른쪽버튼을 클릭했을때 
        // 윈도우의 기본동작을 무시하고, 내가 설정한 행동을 하도록 할 때 사용
        console.log("오른쪽 버튼을 클릭했습니다.");
    })
});