본문 바로가기
목차
JQuery

JQuery(생활코딩 편)

by 지각생 2022. 2. 7.
728x90

 

 

 

 

jQuery - 소개

1. 엘리먼트를 선택하는 강력한 방법과

2. 선택된 엘리먼트들을 효율적으로 제어할 수 있는 다양한 수단을 제공하는

3. 자바스크립트 라이브러리

 


jQuery - wrapper

https://www.youtube.com/watch?v=NonvqKoohKA&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=3


래퍼 소개

래퍼를 쓰는 방법은 크게 2가지 방법

1. JQuery(selector, [context])

2. JQuery(element)

1번째 예제 설명

 

$('ul.foo').click(funtion(){

      $('li', this).css

}

 

 

this는 

[컨텍스트]에 해당하고 this라 함은 자기 자기

즉 여기서는 $('ul.foo')을 일컫는다.

 

그리고

 $('li', this)

는 foo클래스를 가진 ul태그의 li에 해당한다.

 

<ul class="foo">

    <li></li>

</ul>

 

 

 

두번째 예제는 body엘리먼트를 래퍼로 감싼거다.


jQuery - 선택자

https://www.youtube.com/watch?v=W3wqHEJn8Og&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=4 


id선택자 등

각 선택자를 래퍼로 감싸서 요소  선택함.


jQuery - chain

https://www.youtube.com/watch?v=JQdbZWdRtMc&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=5 


 

예제1 - JQuery

#tutorial을 래퍼로 감싸고

.attr로

         href의 값을 해당값으로 바꾸고

         target값을 바꾸고

CSS color값을 바꿈

 

 

예제2 - 자바스크립트

setAttribute할때마다 turorial이라는 변수를 가져와서 실행해야함.

 

console.log(~)해서 실행했는데 undefined되어 있다

이걸 통해

setAttribute의 return값이 없다는걸 알 수 있다.

 

.find('.foo')를 통해 체인 컨텍스트(선택된 요소)를 바꿀 수 있다.

.end()라는 메소드를 쓰면 마지막으로 쓴 traversing을 취소한다.

즉 .find('.foo')이걸 취소해서

다시

$('ul.first')로 돌아간다.

 

즉 traversing를 통해 chain의 대상을 바꿔가며 계속 체인을 이어나갈 수 있다.

생활코딩에서 추천하는 JQuery 강좌 싸이트


jQuery - 이벤트

https://www.youtube.com/watch?v=e-Vuhy_6DsE&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=6 


이벤트란?

4번째 설명 링크가면 자세한 내용 있음

https://opentutorials.org/course/53/56

(로그인을 해야하나? 나는 접속 안됨.  //생활코딩 페이지 링크 걸어둠)

 

trigger는 click me를 호출해주는 역할을 하기 때문에

trigger를 눌러도 click me에서 정의된 함수가 실행된다

 

unbind를 누른 후에는 click me를 눌러도 더이상 함수 실행되지 않는다.

<script type="text/javascript">
            function clickHandler(e){
                alert('thank you');
            }
            $(document).bind('ready', function(){
                 $('#click_me').bind('click', clickHandler);
                 $('#remove_event').bind('click', function(e){
                     $('#click_me').unbind('click', clickHandler);
                 });
                 $('#trigger_event').bind('click', function(e){
                     $('#click_me').trigger('click');
                 });
             })
        </script>

 

bind는 이벤트를 설치.

 

ready에 대해 설명하자면

input버튼에 비해 스크립트가 위쪽이므로 먼저 호출이 된다.

그래서 스크립트 구문이 실행되어 봤자 input버튼은 안 만들어졌기 때문에

없는 id="click_me"를 호출하는것이다.

 

$('#click_me').bind('click', clickHandler);

$('#click_me')해당 래퍼는 클릭 됐을때 바인드 메서드를 실행하고 clickHandler 함수를 호출한다.

 

function(e)는 익명함수이다.

익명함수 쓰는 이유는 이벤트처리 로직은 보통 재활용 되지 않기 때문에 익명함수를 쓴다.

 

unbind를 할땐 bind할때 넣어줬던 인자 그대로 넣어주자

 

첫번째 예제에서는 $(document).bind('ready',function(){}

을 썼지만

 

두번째 예제에서와 같이 $(document).ready(function(){}을 하면 더 간결하다.

 


jQuery - 엘리먼트의 제어

https://www.youtube.com/watch?v=QlvTtu5Lvrw&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=7 


화면을 동적으로 만들 수 있음.


<p>I would like to say:</p>
태그가 있고
<script>$("p").append("<strong>Hello</strong>");</script>
를해주면

이렇게 자식 엘리먼트로 생성된다.


 

엘리먼트 제어 자식, 형제, 부모

자식은 .append

<script>$("p").append("<strong>Hello</strong>");</script>

 

형제는 .after

<script>$("p").after("<b>Hello</b>");</script>

 

부모는 .wrap

<script>$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");</script>

엘리먼트 제어 삭제

엘리먼트를 삭제해보자

$("button").click( function () {
                $("p").remove();
            });
버튼을 클릭했을때 
function () {  $("p").remove();} 
이벤트가 작동한다.

엘리먼트 제어 치환

치환해보자.

<script>$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples        </script>

==><P>를  "<b>Paragraph. </b>"로 치환

 

$("<b>Paragraph. </b>") 이부분은 선택자가 아니라 html을 만들어준다.

 

.replaceAll("p")는 선택자로 <p></p> 태그를 지칭함.


엘리먼트 제어 클래스

클래스 제어는 여러 방법이 있다.

 

addClass() 클래스 추가

hasClass()는 요소가 해당 클래스 가지고 있는지 없는지 체크하는 것임.

removeClass()는 해당 클래스 삭제

toggleClass()는 해당 엘리먼트가 클래스 가지고 있으면 삭제,

                                           클래스를 안 가지고 있으면 추가. (토글 방식으로 작동함) 

 

 <body>
        <p class="blue"> Click to toggle </p>
        <p class="blue highlight"> highlight </p>
        <p class="blue"> on these </p>
        <p class="blue"> paragraphs </p>
        <script>
$("p").click( function () {
                $(this).toggleClass("highlight");
          });
</script>
    </body>

 

클릭하면 class에 highlight 추가되고 다시 클릭하면 highlight 삭제됨 (토글 방식)

 

 


엘리먼트 제어 속성제어

대부분 form과 관련된 input 엘리먼트일텐데 그 엘리먼트가 가지고 있는 value값을 리턴해주는 메소드들

 

 <body>
        <input type="text" value="some text"/>
        <p>
        </p>
        <script>$("input").keyup( function () {
                var value = $(this).val();
                $("p").text(value);
            }).keyup();</script>
    </body>
 
.keyup(function(){})은 사용자가 키보드를 누르고 뗐을때 발생하는 이벤트함수이다.
.text(value)는 엘리먼트의 컨텍트 영역에 전달된 인자를 세팅해줌

.keyup(); keyup이라는 이벤트명을 가진 이벤트 핸들러를 호출하는 트리거 역할

 

초기값을 세팅할때 주로 트리거를 세팅한다.

 

.keydown() 키 입력 시 발생되는 이벤트

.keypress() keydown과 같이 키 입력 시 발생되는 이벤트지만 Enter, Tab 등의 특수키에는 발생하지 않음

.keyup() 키 입력 후 발생되는 이벤트

 


jQuery - 폼

https://www.youtube.com/watch?v=FIw4DZ768MQ&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=8 

  <p>
            <input type="text" />

 

            <span></span>
        </p>
        <script>
            $("input").focus( function () {
                $(this).next("span").html('focus');
            }).blur( function() {
                $(this).next("span").html('blur');
            }).change(function(e){
            alert('change!! '+$(e.target).val());
            }).select(function(){
               $(this).next('span').html('select');
            });
        </script>

 

 

1. $("input")에 포커스되면 .focus 이벤트가 발생하여

해당 익명함수가 실행된다.

2. this는 input태그이다.

3. .next은 형제 중 span태그를 찾겠다. 

4. .html은 컨택트 영역으로 html문서를 넣어줌 "focus"값 준다.

==><span>focus<span>

5. .blur 이벤트시 해당 익명함수 발동

6. .change도 이벤트 핸들러이다.

7. .select라는 이벤트가 있다. 텍스트필드 안에서 텍스트 선택시 발동되는 이벤트

==>아래와 같이 텍스트가 선택되면 발동

<script>
            $("form").submit( function() {
                if ($("input:first").val() == "correct") {
                    $("span").text("Validated...").show();
                    return true;
                }
                $("span").text("Not valid!").show().fadeOut(1000);
                return false;
            });
        </script>

 


jQuery - 탐색

: 체인컨텍스트를 유지하면서 제어의 대상이 되는 엘리먼트를 변경하는 기법

 

https://www.youtube.com/watch?v=3Z3J13D1Vao&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=9 

 

https://api.jquery.com/category/traversing/

 

Traversing | jQuery API Documentation

Create a new jQuery object with elements added to the set of matched elements. Add the previous set of elements on the stack to the current set, optionally filtered by a selector. Add the previous set of elements on the stack to the current set. Get the ch

api.jquery.com

JQuery API Documentation


jQuery - 에니메이션

https://www.youtube.com/watch?v=JO-rQMOl2KI&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=10 


https://opentutorials.org/course/53/52

 

에니메이션 - 생활코딩

에니메이션 2011-07-08 06:07:29 효과란? 자바스크립트와 CSS를 이용해서 HTML엘리먼트에 동적인 효과를 줄 수 있다. jQuery의 효과 메소드를 호출하는 것만으로 간단히 효과를 줄 수 있다. 예제1.       

opentutorials.org

예제1
<script>$('input[type="button"]').click( function(e) {
                var $this = $(e.target);
                switch($this.attr('id')) {
                    case 'fadeout':
                        $('#target').fadeOut('slow');
                        break;
                    case 'fadein':
                        $('#target').fadeIn('slow');
                        break;
                    case 'hide':
                        $('#target').hide();
                        break;
                    case 'show':
                        $('#target').show();
                        break;
                    case 'slidedown':
                        $('#target').hide().slideDown('slow');
                        break;
                    case 'slideup':
                        $('#target').slideUp('slow');
                        break;
case 'mix':
                        $('#target').fadeOut('slow').fadeIn('slow').delay(1000).slideUp().slideDown('slow', function(){alert('end')});
                        break;
                }
            })
</script>

예제2

<script>/* Using multiple unit types within one animation. */
 
            $("#go").click( function() {
                $("#block").animate({
                    width: "300px",
                    opacity: 0.4,
                    marginLeft: "50px",
                    fontSize: "30px",
                    borderWidth: "10px"
                }, 3000);
            });</script>

jQuery - ajax

https://www.youtube.com/watch?v=fiqApu1t1Vc&list=PLrCCNh6y7w2g6U7RX_v-TOefyRPiO32jT&index=11 


$.ajax(settings)

  • jQuery를 이용한 ajax통신의 가장 기본적인 API
  • 주요속성
    • data : 서버에 전송할 데이터, key/value 형식의 객체
    • dataType : 서버가 리턴하는 데이터 타입 (xml, json, script, html)
    • type : 서버로 전송하는 데이터의 타입 (POST, GET)
    • url : 데이터를 전송할 URL
    • success : ajax통신에 성공했을 때 호출될 이벤트 핸들러

 

 

 

 

728x90

댓글