반응형

 

jQuery

 

: 자바 스크립트 라이브러리로 무료 오픈소스 소프트웨어다.

 

자바 스트립트 프로그래밍의 양을 줄여 짧고 간결하게 코드 작성이 가능하다.

메소드 체이닝으로 인해 코드를 계속 연결해서 사용할 수 있다.

 

 

 

사용 방법

 

  • 사용 방법 (jQuery 설정)

 

1. CDN 방식 (콘텐츠 전송 네트워크) : 인터넷 연결이 보장되어 있을 시 사용

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<!-- CDN 방식
    Content Delivery Network(콘텐츠 전송 네트워크)
    용량이 크거나 트래픽이 단기간 집중되는 경우를 대비해 콘텐츠를 CDN서버에 미리 저장해두고
    사용자와 가까운 지점에서 전송하는 방식
    인터넷 연결 보장시 소스코드 관리 및 경로 설정이 필요없는 방식으로 많이 사용됨
 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

</script>
<body>
</body>
</html>

 

 

2. Download 방식 : 인터넷 연결 여부와 관계없이 사용 가능, 반드시 파일이 존재해야 함

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<!-- Download 방식
    사용시 정확한 경로 설정이 필요하며 해당 경로에 반드시 파일이 존재해야 함
    인터넷 연결 여부와 관계없이 컴퓨터 브라우저만으로도 활용 가능한 방식
-->
<script src="../js/jquery-3.7.1.min.js"></script>

</script>
<body>
</body>
</html>

 

 

 

  • 사용 방법 (쓰는 방법)

 

요소일때의 구조

 

함수일때의 구조

 

 

 

  • 사용 비교

 

- Javascript

Var hlist = document.getElementsByTagName(‘h1’)
hlist[0].style.backgroundColor = “yellow”;
Hlist[0].style.color = “red”;

 

-jQuery

var  jq = $(“h1”);
jq.css(“background-color”, “yellow”);
jq.css(‘color’, ‘red’);

 

 

 

문장 구조

 

// 자바스크립트 방식
window.onload = function(){});
document.addEventListener('DOMContentLoaded', function {) {});
window.addEventListener('load', function() {});


// 제이쿼리 방식
$(document).ready(function(){});
$(function() {});

 

 

 

JS와 jQuery의 비교 - 경고창

 

 

  • 요소 비교
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<!-- CDN 방식 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<!-- Download 방식 -->
<!-- <script src="../js/jquery-3.7.1.min.js"></script> -->
<script>
// 문서 준비 코드
// window.onload = function(){
// document.addEventListener('DOMContentLoaded', function {) {
window.addEventListener('load', function() {
    
    let  v_btns = document.querySelectorAll('button');

    v_btns[0].addEventListener('click', function(){
        // 자바스크립트 방식으로 h4 요소에 접근해서 안쪽 text정보를 경고창으로 띄우기
        alert( document.getElementsByTagName('h4')[0].innerText );
        alert( document.querySelector('h4').textContent );
    });
// });

    v_btns[1].addEventListener('click', function(){
        // 제이쿼리 방식으로 h4요소 내부 text정보 경고창 띄우기
        alert( $('h4').text() ); // dom객체를 jquery 객체화 시켜서 반환
    });
});

</script>
<body>
    <button>JS방식</button>
    <button>JQ방식</button>
    <h4>안녕하세요</h4>
</body>
</html>

 

결과 화면1

 

 

 

  • 함수 비교
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>
// JS 문서 준비 코드
// window.onload = function(){
// document.addEventListener('DOMContentLoaded', function {) {
window.addEventListener('load', function() {
    
    let  v_btns = document.querySelectorAll('button');

    v_btns[0].addEventListener('click', function(){
        // alert( document.getElementsByTagName('h4')[0].innerText );
        alert( document.querySelector('h4').textContent );
    });
});

// 제이쿼리 방식 문서준비 코드
// $(document).ready(function(){
$(function() {
    // eq() 메소드 : 인덱스 번호에 해당하는 요소 찾음
    $('button').eq(1).on('click', function(){
            alert( $('h4').text() );
    });
});

</script>
<body>
    <button>JS방식</button>
    <button>JQ방식</button>
    <h4>안녕하세요</h4>
</body>
</html>

 

결과 화면2

 

 

 

JS와 jQuery 이용 - 스타일 변경

 

 

  • 자바 방식
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<script>
window.addEventListener('load', function(){
    // 자바스크립트 방식
    // JS특성상 하나의 요소를 대상으로 설정한다.
    // 전체 h4요소를 대상으로 공통 배경색을 지정하시오
    let v_h4 = document.querySelectorAll('h4');
    for(let i=0; i<v_h4.length; i++) {
        v_h4[i].style.backgroundColor = "orange";
    }
    v_h4[2].style.color = "red";
});
</script>
</head>
<body>
   <h4>jQuery1</h4> 
   <h4>jQuery2</h4> 
   <h4>jQuery3</h4> 
   <h4>jQuery4</h4> 
</body>
</html>

 

결과 화면3

 

 

 

  • 제이쿼리 방식
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(function(){
    // 제이쿼리 방식
    $('h4').css('backgroundColor','blue');
    // 하나의 요소에 접근하고 싶을 때 - eq(): element aueue(요소행렬)
    $('h4').eq(1).css('color','pink');

});
</script>
</head>
<body>
   <h4>jQuery1</h4> 
   <h4>jQuery2</h4> 
   <h4>jQuery3</h4> 
   <h4>jQuery4</h4> 
</body>
</html>

 

결과 화면4

 

 

 

클릭 시 숨김처리

 

 

  • 방식1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
function fnc(p_this) {
    alert(p_this.innerText); // 누른 text가 출력
    // 숨김처리 display=none
    p_this.style.display = "none";
}
</script>
</head>
<body>
    <h4 onclick="fnc(this)">click_hide1</h4>
    <h4 onclick="fnc(this)">click_hide2</h4>
    <h4 onclick="fnc(this)">click_hide3</h4>
    <h4 onclick="fnc(this)">click_hide4</h4>
</body>
</html>

 

결과 화면5-1

 

결과 화면5-2

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
function fnc(p_this) {
    // alert(p_this.innerText); // 누른 text가 출력
    // 숨김처리 display=none
    // p_this.style.display = "none";

    // 에러 발생!
    // DOM객체를 대상으로 jQuery메소드를 실행할 수 없음
    // p_this.hide(); 대신 하단의 방식을 사용해야 함.
    $(p_this).hide();
}
</script>
</head>
<body>
    <h4 onclick="fnc(this)">click_hide1</h4>
    <h4 onclick="fnc(this)">click_hide2</h4>
    <h4 onclick="fnc(this)">click_hide3</h4>
    <h4 onclick="fnc(this)">click_hide4</h4>
</body>
</html>

 

결과 화면6 : click_hide2를 클릭 시 사라짐

 

 

 

  • 방식2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
// 스크립트가 먼저 실행되므로 문서 준비 코드 필요
window.onload = function(){
    
    let v_jsH4 = document.querySelectorAll('h4');
    for(let i=0; i<v_jsH4.length; i++) {
        v_jsH4[i].addEventListener('click', function() {
            console.log(this.innerText); // 클릭하는 것의 텍스트가 출력 JS1 등등
            this.style.display ="none";
        });
    }
};
</script>
</head>
<body>
    <div id="js">
        <h4>JS1</h4>
        <h4>JS2</h4>
        <h4>JS3</h4>
        <h4>JS4</h4>
    </div>
</body>
</html>

 

결과 화면7

 

 

  • => 모두 숨겨질 때 버튼이 보이게 추가 진행
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
button {
  display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
// 스크립트가 먼저 실행되므로 문서 준비 코드 필요
window.onload = function(){
    
    let v_count = 0;
    let v_jsH4 = document.querySelectorAll('h4');

    let v_btn = document.querySelector('button');

    for(let i=0; i<v_jsH4.length; i++) {
        v_jsH4[i].addEventListener('click', function() {
            console.log(this.innerText); // 클릭하는 것의 텍스트가 출력 JS1 등등
            this.style.display = "none";
            v_count++; // 카운트 증가

            // 버튼 보이기 - 조건 모든 요소가 숨겨졌을 때
            if(v_jsH4.length == v_count) {
                v_btn.style.display = "inline";
                v_count = 0;
            }
        });
    } // for end

    v_btn.addEventListener('click', function(){
        // 숨겨진 모든 요소 보이기 처리 >> 하나씩 대상에 적용
        for(let i=0; i<v_jsH4.length; i++) {
            v_jsH4[i].style.display = "block";
        }

        // 버튼 다시 숨김처리
        this.style.display = "none";
    });

};
</script>
</head>
<body>
    <div id="js">
        <h4>JS1</h4>
        <h4>JS2</h4>
        <h4>JS3</h4>
        <h4>JS4</h4>
        <button>show</button>
    </div>
</body>
</html>

 

결과 화면8 : 모든 것을 클릭할 때 버튼 출력

 

 

 

  • 다중 숨기기 보이기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
button {
  display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
// 스크립트가 먼저 실행되므로 문서 준비 코드 필요
window.onload = function(){
    
    let v_count = 0;
    let v_jsH4 = document.querySelectorAll('#js h4');

    let v_btn = document.querySelector('button');

    for(let i=0; i<v_jsH4.length; i++) {
        v_jsH4[i].addEventListener('click', function() {
            console.log(this.innerText);
            this.style.display = "none";
            v_count++;

            if(v_jsH4.length == v_count) {
                v_btn.style.display = "inline";
                v_count = 0;
            }
        });
    } // for end

    v_btn.addEventListener('click', function(){
        for(let i=0; i<v_jsH4.length; i++) {
            v_jsH4[i].style.display = "block";
        }

        this.style.display = "none";
    });

    // 제이쿼리 요소 숨김/보이기
    // $('h4'); // 8개의 값 반환
    // $('#jq h4'); // 4개의 값 반환
    $('#jq h4').on('click', function(){
        // alert(this.innerText); // 클릭하는 것의 텍스트가 출력
        $(this).hide();

        // 조건-모든요소 숨겨졌을 때 버튼 보이기 처리
        // jQuery필터 중 : visible
        // console.log( $('#jq h4:visible').length ); // 다 보이지 않을 때 0출력
        if( $('#jq h4:visible').length <1 ) {
            $('button').eq(1).show();
        }
    });

    $('button').on('click', function(){
        // 요소 보이기 show
        $('#jq h4').show(); // 일괄 보이기 적용

        // 버튼 다시 감추기 hide
        $(this).hide();
    });
};
</script>
</head>
<body>
    <div id="js">
        <h4>JS1</h4>
        <h4>JS2</h4>
        <h4>JS3</h4>
        <h4>JS4</h4>
        <button>show</button>
    </div>

    <hr>

    <div id="jq">
        <h4>JQ1</h4>
        <h4>JQ2</h4>
        <h4>JQ3</h4>
        <h4>JQ4</h4>
        <button>show</button>
    </div>
</body>
</html>

 

결과 화면9

 

 

반응형

'jQuery' 카테고리의 다른 글

[jQuery] 6장 기타 필터  (0) 2024.02.21
[jQuery] 5장 내용 필터  (0) 2024.02.21
[jQuery] 4장 필터 및 기본 필터  (0) 2024.02.21
[jQuery] 3장 jQuery 선택자  (0) 2024.02.21
[jQuery] 2장 jQuery 기초  (0) 2024.02.20