jQuery (23)

반응형

 

$(  ) jQuery 함수

 

 

<!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>
$(function(){
    $('input').css('color', 'blue');
});
</script>
<body>
    <div>
        $('selector'[,context]) <br>
        선택자를 검색할 범위 설정, 생략시 문서 전체에서 선택자를 검색한다.
    </div>

    <form id="frm1">
        <input type="text">
    </form>
    <form id="frm2">
        <input type="text">
    </form>
    <form id="frm3">
        <input type="text">
    </form>
</body>
</html>

 

결과 화면1

 

 

  • 특정 폼만 적용 (컨텍스트 사용)

 

ex)

var myJquery1 = $(“p”);
 var myJquery2 = $(“p”, document.forms[2]);

 

 

 

<!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>
$(function(){
    $('input', $('#frm2')).css('color', 'blue');
});
</script>
<body>
    <div>
        $('selector'[,context]) <br>
        선택자를 검색할 범위 설정, 생략시 문서 전체에서 선택자를 검색한다.
    </div>

    <form id="frm1">
        <input type="text">
    </form>
    <form id="frm2">
        <input type="text">
    </form>
    <form id="frm3">
        <input type="text">
    </form>
</body>
</html>

 

결과 화면2

 

 

<!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>
$(function(){
    $('input', $('#frm2')).css('color', 'blue')
                          .css('backgroundColor','pink')
                          .css('fontSize','1.5em');

    $('form').on('click', function(){
        $('input').css('backgroundColor', 'white'); // 일괄 설정
        $('input', this).css('backgroundColor', 'gold');
    });
});
</script>
<body>
    <div>
        $('selector'[,context]) <br>
        선택자를 검색할 범위 설정, 생략시 문서 전체에서 선택자를 검색한다.
    </div>

    <form id="frm1">
        <input type="text">
    </form>
    <form id="frm2">
        <input type="text">
    </form>
    <form id="frm3">
        <input type="text">
    </form>
</body>
</html>

 

결과 화면3-1 : 클릭 전

 

결과 화면3-2 : 클릭 후

 

 

 

버튼 클릭 시 정보 삽입

 

 

  • 문자열로 일괄 생성
<!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>
$(function(){
    // 문자열로 일괄 생성
    $('[type=button]').eq(0).on('click', function(){
        let tagP = $("<p title='🎁' onclick='f_click(this)'>Hi🎁 jQuery!!</p>");
        $('div').html(tagP);
        // $('div').append(tagP); // 이걸 사용해도 되지만 연속적으로 클릭 시 계속 출력됨
        
        // 부모.append(자식)
        // $('div').append(tagP); // append()는 제이쿼리 메소드이며, appendChild()는 원시 DOM 요소만 대상으로 함
        // 자식.appendTo(부모)
        // tagP.append($('div'));
    });
});
</script>
<body>
    <input type="button" value="문자열로 일괄 생성">
    <input type="button" value="요소만 생성 후 속성 지정하여 생성">
    <div></div>
</body>
</html>

 

결과 화면4 : 문자열로 일괄 생성 클릭 시 추가

 

 

=> 글자를 클릭 시 배경색 변경

<!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>
$(function(){
    // 문자열로 일괄 생성하기 - $("html")
    $('[type=button]').eq(0).on('click',function(){

        let $tagP = $("<p title='🎁' onclick='f_click(this)'>Hi🎁 jQuery!!</p>");
        $tagP.appendTo('div');
    });
    
function f_click(p_this){
    p_this.style.backgroundColor = 'olive';
}
</script>
<body>
    <input type="button" value="문자열로 일괄 생성">
    <input type="button" value="요소만 생성 후 속성 지정하여 생성">
    <div></div>
</body>
</html>

 

결과 화면5

 

 

 

  • 요소만 생성 후 속성 지정하여 생성
<!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>
$(function(){
    // 문자열로 일괄 생성하기 - $("html")
    $('[type=button]').eq(0).on('click',function(){      //속성type이 button인거

        let $tagP = $("<p title='🎁' onclick='f_click(this)'>Hi🎁 jQuery!!</p>");   //제이쿼리로 선언된변수다라는 뜻으로 변수명앞에 $붙여준다
        // $('div').html($tagP);     //innerhtml 한번만 추가됨
        // $('div').append($tagP);   //appendChild 계속 추가됨   // append() 는 제이쿼리 메소드이며, appendChild()는 원시 DOM요소만을 대상으로 함
        // 부모.append(자식)
        // 자식.appendTo(부모)
        $tagP.appendTo('div');
    });

    // 요소의 껍질만 생성하고 추가정보는 두번째 인자에 객체 형식으로 작성하기
    // 요소선택자:입력양식선택자
    $('input:button').eq(1).on('click',function(){
        $("<p></p>", {
            title: '🐱‍🐉',
            // click: function(){   // 이벤트만 설정되고 이벤트 발생시점에 함수 호출
            onclick: function(){    // 이벤트 핸들러로 설정되었기 때문에 함수가 바로 실행되어 스타일 반영
                // this.style.backgroundColor = "pink";
                $(this).css("backgroundColor", "pink");
            },
            text: '🐱‍🐉공룡 고양이'
        }).appendTo($('div'));

    });

});

function f_click(p_this){
    p_this.style.backgroundColor = 'olive';
}
</script>
<body>
    <input type="button" value="문자열로 일괄 생성">
    <input type="button" value="요소만 생성 후 속성 지정하여 생성">
    <div></div>
</body>
</html>

 

결과 화면6

 

 

 

동적 버튼 & 정적 버튼

 

 

<!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(){
  let btn = $("<input type=\"button\" value=\"동적 버튼\">");
	$('body').append(btn);
});

</script>
</head>
<body>
    <input type="button" value="정적 버튼">
</body>
</html>

 

결과 화면7

 

 

=> 버튼 클릭 시 이미지 보이기 & 이미지 클릭 시 css 추가

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
img {
	width: 100px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(function(){
  let btn = $("<input type=\"button\" value=\"동적 버튼\">");
	$('body').append(btn);
  
	$('[value="동적 버튼"]').on('click',function(){

		let v_img = $('<img src="../images/ala.jpg" alt="꽐라" onclick="f_fnc(this)">');
		$('body').append(v_img);
	});

	$('[value="정적 버튼"]').on('click',function(){
		/* $('<img>',{
			'src' : '../images/lion.jpg',
			alt : '사자어흥',
			"click" : function(){
				$(this).css('border','3px dashed purple').css('border-radius','10px');
			}
		}).appendTo($('body')); */

		$('body').append($('<img>',{
			'src' : '../images/lion.jpg',
			title : '사자어흥!!!!!!',
			"click" : function(){
				$(this).css('border','3px dashed purple').css('border-radius','10px');
			}
		}));
	});
});

let f_fnc = function(p_this){
	$(p_this).css('border','3px double brown');
}; 

</script>
</head>
<body>
    <input type="button" value="정적 버튼">
</body>
</html>

 

결과 화면8-1 : 정적 버튼, 동적 버튼 클릭 시

 

결과 화면8-2 : 각각의 사진 클릭 후

 

 

 

.text(), .html(), .val(), each()

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>비투비 사랑해</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
    <p>1<span>BTOB</span></p>
    <p>1<span>Born TO Beat</span></p>
    <p>1<span>비투비</span></p>

    <input type="button" value="text">
    <input type="button" value="html">
    <input type="button" value="each">
    😪 <br><br>

    <!-- <button>객체대상 each</button>
    <button>선택자대상 each</button> -->

<script>
    // 자바스크립트 방식으로 요소의 정보를 가져올 때 innerHTML, innerText, textContent
    // 자바스크립트 방식으로 입력양식요소의 정보에 접근할 때 value

    // 제이쿼리 방식으로는 각 html(), text(), val() 메소드로 대체

    $('[value=text]').on('click',function(){
        // 모든 대상요소의 태그를 포함하지 않는 문자 정보를 가져옴
        console.log($('p').text());
    });

    $('[value=html]').on('click',function(){
        // 대상요소가 여러개라도 첫번째 대상요소의 태그를 포함한 정보만 가져옴
        console.log($('p').html());
        console.log($('input').val());
    });

    $('[value=each]').on('click',function(){
        // console.log( $('p').length );

        $('p').each(function(i,v){
            console.log( $('p') );  // 모든 p요소를 p요소의 갯수만큼 반복적으로 제공
            //console.log(this);      // p요소를 순차적으로 반환
            //console.log(i); // 각 요소의 index 반환
            //console.log(v); // this와 동일하게 대상요소(현재 p)를 순차적으로 반환

            // 요소의 정보 반환
            //console.log($('p').html()); // 전부 같은 첫번째 항목 정보만을 반환하므로 실패..
            // console.log($(this).html());     // 순차적 정보를 반환
            // console.log($(v).html());        // 순차적 정보를 반환
            console.log($('p').eq(i).html());   // 순차적 정보를 반환
        });
    });
</script>
</body>
</html>

 

결과 화면9

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>비투비 사랑해</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
    <p>1<span>BTOB</span></p>
    <p>1<span>Born TO Beat</span></p>
    <p>1<span>비투비</span></p>

    <button>객체대상 each</button>
    <button>선택자대상 each</button>

<script>
    let $btn = $('button');

    let obj = {
        key1 : 'value1',
        key2 : 'value2',
        key3 : 'value3'
    };

    // 객체 대상 each문법 - $.each(객체,콜백)
    $btn.eq(0).on('click',function(){

        $.each(obj,function(i,v){
            console.log(this[0]);  // 객체의 순차적인 value정보를 반환
            console.log(i);  // 객체의 순차적인 key정보를 반환
            console.log(v);  // this 와 동일
        });
    });

    $btn.eq(1).on('click', function(){
        
        // 선택자 대상 each문법 - $('선택자').each(콜백)의 선택자 위치에 객체를 넣었을 때
        $(obj).each(function(i,v){
            console.log(this); // 객체 한 덩어리 자체를 반환
            console.log(i); // 객체 한 덩어리를 가리키는 index0을 반환
            console.log(v.key1); // this와 동일
        });

        // 객체 대상 each문법 - 선택자를 대상으로 했을 때
        // $.each('p', function(){});
        // Cannot use 'in' operator to search for 'length' in p
        // 객체 대상 문법은 대상인 객체의 갯수만큼 함수를 호출하는데,
        // 현재 대상이 갯수를 셀 수 있는(length속성을 갖는) 대상이 아니므로 오류를 발생시킴!
    });


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

 

결과 화면10 : each 클릭 시 화면

 

결과 화면11 : 선택자대상 each 클릭 시 화면

 

 

반응형

'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] 1장 jQuery와 사용법  (0) 2024.02.19
반응형

 

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
1 ··· 5 6 7 8