클라우드 융합 Full-stack 웹 개발자 양성과정/HTML, CSS, JavaScript, j-Query

j-Query - 응용예시, 이벤트, 시각적인 효과 메소드

thesunset 2022. 11. 2. 20:05

11. 응용예시


1)  게시판 만들기

<table>
    <thead>
        <tr>
            <th>글번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>조회수</th>
            <th>작성일</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>6313</td>
            <td>청담동점집.압구정점집.신사동점집</td>
            <td>태을천천상화</td>
            <td>5</td>
            <td>2022.10.31</td>
        </tr>
        <tr>
            <td>6312</td>
            <td>도곡동점집.삼성동점집.역삼동점집</td>
            <td>1setew116</td>
            <td>2</td>
            <td>2022.10.31</td>
        </tr>
        <tr>
            <td>6191</td>
            <td>올해 부자되게 해주세요 제발...</td>
            <td>대구포에버</td>
            <td>10</td>
            <td>2022.10.19</td>
        </tr>
    </tbody>
</table>

- 게시글을 클릭하면 보여줄 곳

선택된 게시글 정보 : 
<label id="l1">글번호</label> /
<label id="l2">제목</label> /
<label id="l3">작성자</label> /
<label id="l4">조회수</label> /
<label id="l5">작성일</label>

- 스크립트와 스타일 미리 지정하기 (사전작업)

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <style>
        tbody>tr:hover{
            cursor: pointer;
            background-color: lightgray;
            color: white;
        }
    </style>

- 게시글 번호부터 순차적으로 접근해보면(console창에 찍어보기)

$(function(){

    $('tbody>tr').click(function(){
                console.log($(this).children().eq(0).text());
                console.log($(this).children().eq(1).text());
                console.log($(this).children().eq(2).text());
                console.log($(this).children().eq(3).text());
                console.log($(this).children().eq(4).text());

- 현재 선택된($(this))요소의 자식들 중에서  0~4번째 요소(<td>??</td>)의 innerText속성값을 가져오기

$('#l1').text($(this).children().eq(0).text());
$('#l2').text($(this).children().eq(1).text());
$('#l3').text($(this).children().eq(2).text());
$('#l4').text($(this).children().eq(3).text());
$('#l5').text($(this).children().eq(4).text());

- 반복문으로 코드 간결하게 만들기

$(this).children().each(function(index, value){
    $('#l'+(index+1)).text($(value).text());
});

2) 부트스트랩


https://www.w3schools.com/

: 특히 modal기능 많이 사용할 예정

: 필요한 기능 찾아서 부여하면 됨

<head></head>태그 내에 외부스타일 속성 부여 

 

- 구글에 'bootstrap template' 검색하고 시작하면 틀이 잡혀있어 더 쉬울 수 있음

 

<!-- 버튼 -->

<button class="btn btn-primary">로그인</button>
<button class>로그인</button>
<button>로그인</button>
<button>로그인</button>
<button>로그인</button>
<button type="button" class="btn">Basic</button>

<!-- 꼭 버튼요소에만 스타일을 부여할 수 있는 것은 아님 -->

<div class="btn btn-danger">입력</div>

<br>

<br><br>

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Open modal
</button>

<!-- The Modal -->
<div class="modal" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">

<!-- Modal Header -->
<div class="modal-header">
    <h4 class="modal-title">Modal Heading</h4>
    <button type="button" class="close" data-dismiss="modal">&times;</button>
</div>

<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>

<!-- Modal footer -->
<div class="modal-footer">
  <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>

12. 이벤트


1) 이벤트 핸들러(이벤트 발생 시 실행될 코드들)

(1) 방법1. 이벤트 메소드를 통한 연결 

: $('선택자').이벤트메소드(function(){
    이벤트 발생 시 실행할 내용
})

<h4 id="test1">클릭해보세요.</h4>

<script>
$(function(){ //문서가 다 로딩되고 나서 바인딩
    $('#test1').click(function(){
        //이런 이벤트 핸들러를 실행시켜라 
        $(this).html('클릭되었습니다.');
    });

    //더블클릭
    $('#test1').dblclick(function(){
        $(this).css('color', 'red');
    });

});
</script>

(2) 방법2. on메소드를 쓰는 방법 

[표현법]
$('선택자').on('이벤트명', function(){
    이벤트 발생 시 실행할 내용
}); 

<h4 id="test2">마우스클릭 및 올려보세요.</h4>

- 클릭 : 'click'

$(function(){
    $('#test2').on('click', function(){
        $(this).css('background', 'red').text('클릭');
    });


- 올려보세요 : 'mouseenter'

$('#test2').on('mouseenter', function(){
    $(this).css('color', 'blue');
});


방법2의 장점 : 한 번에 여러 이벤트를 걸 수 있음 
<예시1>

    $('#test2').on({'click': function(){
        $(this).css('background', 'red').text('클릭');
    },'mouseenter' : function(){
        $(this).css('color', 'blue');
   }});

<예시2>

$('#test2').on({
    'mouseenter' : function(){
        $(this).css('background', 'yellowgreen').text('마우스올림');

    }, 
        'mouseout' :function(){
        $(this).css('background', 'green').text('마우스 나감');
    },
        'click' : function(){
            //클릭이벤트가 발생할 경우 기준의 mouseenter, mouseout이벤트 핸들러 제거
        $(this).off('mouseenter').off('mouseout');
        //off('삭제할 이벤트명') : 이벤트핸들러 제거 메소드 
        $(this).css('background', 'orangered').text('이벤트제거');

    }
});

(3) 방법2. on메소드를 쓰는 방법2

[표현법]
$('상위요소선택자').on('이벤트명', '하위요소 선택자', function(){
    이벤트 발생 시 실행할 내용
});

 

    <div id="wrap">
        <h4>h4요소를 클릭해보세요.</h4>
        <h5>h5요소를 클릭해보세요.</h5>
    </div>

- h4는 #wrap의 자식

$('#wrap').on('click', 'h4', function(){
    alert('클릭');
});
// == $('#wrap h4').on('click', function(){}); 같은 것

현재 이 문서상의 모든 요소들 중에서 h1~ h6에 대해서 클릭이벤트를 주고 싶다.
$(document) : 이 문서 객체를 jQuery화 시킨 것

    $(document).on('click', 'h1, h2, h3, h4, h5, h6', function(){
        console.log($(this));
        $(this).css('color', 'aqua');
    })

2) 동적으로 만들어진 요소에 이벤트 적용


동적으로 만들어진 요소 :
처음에 문서 로딩 시에는 존재하지 않다가 나중에 새롭게 만들어지는 요소

-  요소 생성

<div id="wrap2" style="border: 1px solid red;">
    <h6>기존에 존재하는 요소</h6>
    <!-- 바로 여기에 새롭게 요소 추가 -->
</div>

방법1. 이벤트 메소드 호출 => 동적으로 만들어진 요소에 이벤트 적용 안됨

$('#wrap2>h6').click(function(){
    $('#wrap2').append('<h6>새롭게 추가된 요소</h6>');
});

방법2. on메소드=> 동적으로 만들어진 요소에 이벤트 적용 안됨

$('#wrap2>h6').on('click', function(){
    $('#wrap2').append('<h6>새롭게 추가된 요소</h6>');
})

방법3. on메소드2
문서 로딩하는 시점에 있기 때문에 실행이 정상적으로 됨

$('#wrap2').on('click', 'h6', function(){
    $('#wrap2').append('<h6>새롭게 추가된 요소</h6>');
})

3번은 대표적인 예시로 웹툰 댓글이 div요소 웹툰올라오자마자 생기는 것이 아닌 누군가 댓글을 달 때 생기는 것과 같음
(문서를 처음 로딩할 때 생기는 것이 아닌)

동적으로 만들어진 요소에 기존에 존재하는 동일한 이벤트를 적용하고자 한다면
반드시 3번 방법으로 해야 함****

 

1, 2번은 호출하는 시점이 문서가 로딩된 후이기 때문에 적용이 되지 않음

 

3) 일회성 이벤트 


: 이벤트를 딱 한 번만 연결할 때 사용
[표현법]
$('선택자').one('이벤트명', function(){
    이벤트 발생 시 실행할 내용
});

<h5 id="test3">단 한 번만 실행할 것</h5>

<script>
    $(function(){
        $('#test3').one('click', function(){
            alert('처음이자 마지막 이벤트 발생');
        });
    })
</script>

4) 키보드 관련 이벤트 


키가 눌려졌을 때 발생하는 이벤트
- keydown : 키보드의 모든 키가 눌릴 때 발생 
- keypress : 키보드의 function키, 기능키, 한글을 제외한 나머지 키가 눌릴 때 발생 
키가 떼어질 때 발생하는 이벤트
- keyup: 키가 위로 올라올 때 발생

    <input type="text" id="test4">

    <script>
        $(function(){
            $('#test4').keydown(function(){
                // console.log('눌림');

                // console.log($(this).val().length);//실시간 글자수 세기
            });

            $('#test4').keyup(function(){
                // console.log('올라옴');
            })
        });

5) 글자 수 세기 예제  


<div style="border: 1px soild lightgray;">
    150자 이내로 작성하시오. <br> <br>
    <textarea id="content" cols="40" rows="10" style="resize:none" maxlength="150"></textarea>

    <br>
    <hr>

    <span id="count">0</span> / 150
</div>

<script>
    $(function(){
        $('#content').keyup(function(){ //keydown쓰면 한 칸씩 밀려서 keyup을 씀
            $('#count').text($(this).val().length);

        })
    })
</script>

6) 체크박스관련 메소드

<div class="wrapper">
    <div>

        <input type="checkbox" id="all" class="batch"><label>전체</label>
        <input type="checkbox" id="jp" class="batch"><label>일식</label>
        <input type="checkbox" id="ch" class="batch"><label>중식</label>
    </div>
        <hr>
    <div>
        <input type="checkbox" class="jp chk"><label>초밥</label>
        <input type="checkbox" class="jp chk"><label>오코노미야끼</label>
        <hr>
        <input type="checkbox" class="ch chk"><label>유산슬</label>
        <input type="checkbox" class="ch chk"><label>소룡포</label>
    </div>
</div>

- 전체 선택

$(function(){

	//전체 체크 되어있다가 하나 해제하면 전체선택 박스 해제 
    $('.batch').on('change', function(){
        if($(this).prop('checked')==false){
            $('#all').prop('checked', false);
        }
    });

    $('#all').on('change', function(){
        //console.log($('#all').prop('checked')); //checked되면 true 안되면 false
        var $all = $('#all').prop('checked'); //attr()은 안되는 경우가 있어서 prop사용

        if($all){
            $('.chk, .batch').prop('checked', true); //모두 체크 
        } else{
            $('.chk, .batch').prop('checked', false); //모두 체크 해제
        }
    });

- 일식

    $('#jp').on('change', function(){
        var $jp = $('#jp').prop('checked');

        if($jp){
            $('.jp').prop('checked', true);
        } else{
            $('.jp').prop('checked', false);
        }
    });

- 중식

    $('#ch').on('change', function(){
        var $ch = $('#ch').prop('checked');

        if($ch){
            $('.ch').prop('checked', true);
        }else{
            $('.ch').prop('checked', false);
        }
    });

13. 시각적인 효과 메소드


1) 시각적인 효과 메소드 (Effect메소드)

페이지 내에서 애니메이션 효과를 만들기 위해 사용하는 메소드 집합
- 사용할 이미지 

<img id= 'pizza' src="https://mp-seoul-image-production-s3.mangoplate.com/203706/1066821_1607689884043_40646?fit=around|738:738&crop=738:738;*,*&output-format=jpg&output-quality=80">


(1)  show(), hide(), toggle()

:  선택된 요소가 점점 커지면서 보이고 점점 작아지면서 사라지게 하는 메소드

<button id="hide">숨기기</button>
<button id="show">보이기</button>
<button id="toggle">토글</button>
$(function(){
    //숨기기 버튼
    $('#hide').click(function(){
        $('#pizza').hide(3000); //시간(ms)
    });

    //보이기 버튼
    $('#show').click(function(){
        $('#pizza').show(3000);
    });

    //toggle() 스위치로 따지면 on off 기능
    $('#toggle').click(function(){
        $('#pizza').toggle(1000);
    });


(2)  fadeIn(), fadeOut(), fadeToggle() 

: 선택된 요소가 점점 투명해지면서 사라지고, 점점 선명해지면서 보여지게 하는 메소드

<button id="fadeOut">숨기기</button>
<button id="fadeIn">보이기</button>
<button id="fadeToggle">토글</button>
//인자값으로 ms단위로 시간을 지정할 수 있음

$('#fadeOut').click(function(){
    $('#pizza').fadeOut(3000); //시간(ms)
});

$('#fadeIn').click(function(){
    $('#pizza').fadeIn(3000);
});

$('#fadeToggle').click(function(){
    $('#pizza').fadeToggle(1000);
});


(3) slideDown(), sildeUp()

선택된 요소가 점점 아래로 내려오면서 나타났다가
점점 위로 올라가면서 사라지게 하는 메소드 

고객센터 FAQ
FAQ : Frequently Asked Question (자주묻는 질문)

- 미리 스타일 부여 

<style>
    div{
        background-color: beige;
        width: 300px;
        height: 40px;
        line-height: 40px;
        border-radius: 10px;
        border: 1px dotted pink;
        padding: 8px;
        color: orchid;
    }

    p{
        border: 1px solid lightgoldenrodyellow;
        width: 300px;
        height: 100px;
        border: 10px;
        padding: 8px;
        color: mediumvioletred;
        display: none;
    }

</style>

질문은 div

답변은 p

  <div>Q. 반품은 언제되나요?</div>
  <p>A. 반품은 3~4달정도 소요됩니다.</p>

  <div>Q. 상품위치를 알고 싶습니다.</div>
  <p>A. 택배사에 문의하세요.</p>

  <div>Q. 이 사이즈가 있나요?</div>
  <p>A. 네, 있습니다.</p>

  <div>Q. 전화통화 가능한 시간이 언제인가요?</div>
  <p>A. 회사에 전화가 없습니다.</p>

  <div>Q. 판매자가 연락이 안됩니다.</div>
  <p>A. 경찰에 신고하세요.</p>

$(this) : 현재 클릭 이벤트가 발생한 div요소
$(this).next() : 현재 클릭 이벤트가 발생한 div요소 바로 뒤에 있는 p요소

$(function(){
	  $('div').click(function(){
      		 var $p = $(this).next();

jQuery 방식으로 선택된 요소를 담아둘 때 변수명 앞에 $를 붙이곤 함

css() : 선택된 요소들의 스타일에 관한 기능을 수행하는 메소드 
=> 속성명만 인자값으로 전달하게 되면 해당 속성값을 반환해준다(getter/setter역할을 동시에 수행)

    if($p.css('display') == 'none'){ //display값이 none일 땐 열어주고 

        //기존에 열려있던 p태그를 닫아주자.
        $p.siblings('p').slideUp(1000);
        $p.slideDown(1000);
    }else{ //none이 아닐 때 닫아줌
        $p.slideUp(1000);
    }
});