본문 바로가기

콩's EDUCATION/콩's Jquery

[KITRI] Jquery 2장

JQUERY 2장


http://192.168.103.151:8081/jquery/subjects.html

 

-JQUERY

 

<자바스크립트 실습>

java script 이용하여 계산기 만들기

java script 이용하여 설문지 작성하기

 

<자바스크립트 review>

java script 기본 문법 + 기본 api + event 처리

자바스크립트언어 : 넷스케이프사 개발 언어

각 브라우저 지원 ( 자바 언어 :  JDK TOOL 설치)

기본 api : 별도의 api 설치 없이 브라우저에서 지원

dom객체등의 문서객체

window, document, navigator 등의 브라우저관련 객체등

FORM객체

 

EVENT :

1. 사용자입력(FORM, A, IMG....)

2. 입력내용 유효성 검사

CSS

3. 태그 레이아웃 표현

자바스크립트 이벤트 처리

 

 

 

EVENT 1

EVENT 2

 

자바스크립트  DOM 객체 이용

<INPUT TYPE=BUTTON ID=”A”>

...

<SCRIPT>

DOCUMENT.GETELEMENTBYID

(“A”).ONCLICK=함수

a.addEventListener(‘click’, f1, false)

a.addEventListener(‘click’, f2, false)

-if(window.event){
window.event.cancelBubble = true;

}

else{

e.stopPropagation()

}

 

HTML 태그 INLINE 방식

<INPUT TYPE=BUTTON

ONCLICK=함수>

 

 

1. 동일 태그 동일 이벤트 처리함수 1개 지정

2. IE와 브라우저 종류 따라 이벤트처리방식 다르다

브라우저 종속적

(크로스 브라우징X)

1. 동일 태그 동일 이벤트 처리함수 여러개 지정

2. IE와 브라우저 종류 따라 이벤트처리방식 다르다

IF-ELSE

jquery : 장점 :

dom객체 특정 태그 검색...,

이벤트처리 단순 문법


java script 기본 api 외에 추가 api 많음

추가 api jquery 라는 java script library(api) 존재(추가 설치 sw)

jquery:document 특정 html태그, 속성, 텍스트  객체화해서 select

, 문서 내에서 특성 태그를 찾아 조작하고 태그를 삽입 수정 삭제하며 이벤트 처리를 하는 api 가 주로 제공

 

<브라우저에서 지원안하므로 jquery api 다운로드 필요>

 

java script : 브라우저 지원 스크립트 언어

자바스크립트 문법과 기본 api 그대로 사용하며 추가 dom 태그 검색과 이벤트 처리 단순api 사용

<script type=text/javascript> jquery </script>

js\webcontent\a.html

js\webcontent\js\a jquery-1.11.1.js

 

1. jquery api 다운로드

 

http://jquery.com/download/

 

jquery.com : jquery-1.xxx.js

(버전 2.xxx대는 ie 8 에서 미지원)

jquery.com : jquery-1.xxx.min.js

==>  압축본 / 내용 차이 없음

2. html 파일 내부

2-1. 다운로드

<script src=js/jquery-1.11.1.js> jquery </script>

 

2-2. 다운로드필요없다(인터넷 연결 가능상태)

-cdn 사이트 연결도 가능

link jQuery's CDN provided by MaxCDN

To use the jQuery CDN, just reference the file directly from http://code.jquery.com in the script tag:

1

2

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<jquery  시작>

<script src="jquery-1.11.0.js"></script>

<script type="text/javascript">

$(document).ready ( 함수(){........}   );

</script>

html / java script / jquery($) / servlet / jsp / el($) / jstl

 

$:JQuery 객체 대신 또다른 키워드

-$(??????) selecor 문법

-jquery 함수

-이벤트 함수

 

$(‘a’)====> selector

$(‘a[href=”link.html”]’)====> selector

document.getElementsByTagName(“a”);

document.getElementsByClassName(“link”);

document.getElementById(“aa”);

 

 

텍스트 상자: 자바스크립트 함수 시작
window.onload=function(){
document.getElementById("d").innerHTML=...
}

 

 

 

 

 

 

$(selector).메소드1().메소드2();

 


selector 표현방법

$(‘a’) ==> a태그 selector 문법

$(‘.clas’) ==> <a class=”clas” 클래스속성 부여된 태그selector 문법.

$(‘#id’) ==> <a id=”id” id 속성 부여된 태그 selector 문법

<자바스크립트 dom 객체 태그 검색 select>

<a href=”b.html” id=”aa” class=”link >

<a href=”c.html” >

<p class=”link” >

document.getElementsByTagName(“a”);

document.getElementsByClassName(“link”);

document.getElementById(“aa”);

 

 

 

$(‘a’).

$(‘p a’).

$(‘p > a’).

$(‘input[type=text]’).

$(‘input:checked’).

$(tr:even)

 

$(selector).메소드1().메소드2();

 

메소드
$(document).ready(
함수명)

$(selector).css(“color”, “red”)

$(selector).addClass(“클래스명”)

$(selector).removeClass(“클래스명”)

$(selector). toggleClass (“클래스명”)

true/false<=$(selector). hasClass (“클래스명”)

==>클래스명은 style 태그에서 .클래스명{....}

 

 

$(“body”).html(“<h1>제목</h1>”);

==> setter메소드역할

$(“body”).html();

==>getter메소드역할

 

jquery 시작

style

문서 내용 설정/조회

ready

css

html(“html태그해석”)

html()

$(document)

.ready

addClass

removeClass

toggleClass

hasClass

text(“문자열”)

text()

----------

val(“...”)

val()


테이블태그:5:짝수행 노랑색 / 홀수행 파랑색

$(테이블태그:even / odd)

1,3,5 : index0==> even

2,4:odd

addClass(클래스명)

removeClass(클래스명)

===> filtering : 태그 select 했는데 위치 값 다르게 속성 설정

$(“tr:even”)

$(“tr”).filter(“:even”)

css(요소명, )

 

$(태그명:xxxx)

==> $(태그명).filter(xxx)

 

 

 

태그 검색 함수

$(태그명).filter([type=text])

$(태그명).filter(:first)

 

검색하던 현재 태그 이전 태그 되돌아가기

 

end()

태그 내부 내용 설정/조회

html(매개변수)/html()

text(매개변수)/text()

val(매개변수)/val()

태그 내부 속성 설정/조회

$(“a”).attr(“href”,”a.html”)/attr(“type”)

val(매개변수)/val()

==>

attr(“value”,””)/attr(“value”)

반복

-$():배열일때 사용

$().each(function(){

this=>현재선택

this.변수

$(this).함수

반복 수행}  )

태그 추가 / 삭제 /이벤트 처리 함수

 

 

 

css / class(css 레이아웃 그룹 묶음)

<a style=”color:red; background-color: silver” >

<a class=”클래스명” >

==>
여러개 태그에 style 동일하겢 적용 필요

 


<이클립스에서 jsdt 플러그인 추가>

이클립스 help - marketplace - jsdt검색 - jsdt jquery 인스톨

 

 

21207933532012811450FB

 

 

 

설치 후 다시시작 restart now

 

 

 

프로젝트를 선택하고 Properties 를 열고

javascript > Include Path 를 클릭

jquery라이브러리 추가



2111DF345320117736855D

 

 

 

 

적용된 화면

226EC5395320120A260941

 

 

<style>

.red-silver{

color:red; background-color: silver

}

 

<a class=

addClass / removeClass

선택한 객체 문자열값 추출/설정

val(‘value’)/text(“”)/html(‘’)

filter / find / clone / appendTo(8가지)

each ===>

$(“input:checked”).each(function(){

 $(this).css()

});

 

jquery의 태그추가

$("select").append("<option>ibatis</option>");

   $("option:last").attr("value","ibatis과목");

   alert($("option:last").attr("value"));

 

 

이벤트

$(‘input’).on(‘click’, function(){.....});

 keyup /

checkbox, radio, select-option:change

 

$(‘input’).on(‘click’, function(){.....});

$(‘input’).off(‘click’)

bind(=on)/unbind(=off)

$(‘input’). click(function(){.....});

 

setValue/getValue

 jQuery에서 이용할 수 있는 이벤트들을 알아본다.

- click()

 $(document).ready(function(){

  $("p").click(function(){

    $(this).hide();

  });

});

 

- dblclick()

$(document).ready(function(){

  $("p").dblclick(function(){

    $(this).hide();

  });

}); 

 

- mouseenter()

 $(document).ready(function(){

  $("#p1").mouseenter(function(){

    alert("You entered p1!");

  });

});

 

- mouseleave()

 $(document).ready(function(){

  $("#p1").mouseleave(function(){

    alert("Bye! You now leave p1!");

  });

});

 

click

- mousedown()

$(document).ready(function(){

  $("#p1").mousedown(function(){

    alert("Mouse down over p1!");

  });

}); 

 

- mouseup()

$(document).ready(function(){

  $("#p1").mouseup(function(){

    alert("Mouse up over p1!");

  });

}); 

 

- hover()

$(document).ready(function(){

  $("#p1").hover(function(){//mouseenter / mouseleave

    alert("You entered p1!");

    },

    function(){

    alert("Bye! You now leave p1!");

  }); 

}); 

 

- focus() & blur()

 <script>

$(document).ready(function(){

  $("input").focus(function(){

    $(this).css("background-color","#cccccc");

  });

  $("input").blur(function(){

    $(this).css("background-color","#ffffff");

  });

});

</script>

Name: <input type="text" name="fullname"><br>

Email: <input type="text" name="email">

[

 

마우스이벤트 / 입력양식이벤트

 

trigger

$(selector1).click(function(){});

 

setTimeOut($(selector2).trigger(click); 3000

 

 

http://api.jquery.com/category/events/

 http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/category/forms/

17 animation :

자바스크립트 + jquery api + 애니메이션 api

플러그인

 

part3 AJAX

AJAX

XMLHttpRequest

CROSS DOMAIN

 

PART 4  플러그인

 

 

 

 

 

예제1. bind, unbind, trigger 이용한 이벤트의 설치, 제거, 호출

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<html>

    <head>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

        <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>

    </head>

    <body>

        <input id="click_me" type="button" value="click me" />

        <input id="remove_event" type="button" value="unbind" />

        <input id="trigger_event" type="button" value="trigger" />

    </body>

</html>

예제2. 이벤트 헬퍼

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<html>

    <head>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

        <script type="text/javascript">

            function clickHandler(e){

                alert('thank you');

            }

            $(document).ready(function(){

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

                 $('#remove_event').click(function(e){

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

                 });

                 $('#trigger_event').click(function(e){

                     $('#click_me').trigger('click');

                 });

             })

        </script>

    </head>

    <body>

        <input id="click_me" type="button" value="click me" />

        <input id="remove_event" type="button" value="unbind" />

        <input id="trigger_event" type="button" value="trigger" />

    </body>

</html>

1. http요청1? id=a&pw=b

5. . http요청2?id=c&pw=d

 
java script / jquery



 

 

 

 

 

 


<ajax>

  • Asynchronous JavaScript and XML 약자
  • 자바스크립트를 이용해서 비동기식으로 서버와 통신하는 방식. XML 이용한다.
  • XML 이용할 필요는 없고, 최근에는 json 많이 이용한다.
  • 비동기식이란 여러가지 일이 동시적으로 발생한다는 뜻으로, 서버와 통신하는 동안 다른 작업을 있다는 의미

1. AJAX(Asynchronous Javascript and XML)란 무엇인가?

 

Ajax 예를들면

네이버나 다음같은 포털사이트에 가보면

메인페이지에서 뉴스 등 밑에 < , > 요런 버튼을 눌렀을 때 페이지가 Reloading 되지 않고 뜨는걸 볼 수있다.

 

보통 웹의 흐름에서는 새로운 URL로 호출 되면서 페이지가 새로 뿌려지지만,

AJAX를 사용하면 일부만을 로드해올 수 있는 것이다.

이름처럼 비동기 통신을 통해서.

 

1. 자바 스크립트 ajax

2. jquery ajax

$.ajax(‘/a.jsp’ , {success: div태그결과출력})

 

$.post(‘/a.jsp’ , {success: div태그결과출력})

 

$.get(‘/a.jsp’ , {success: div태그결과출력})

 

 서버, 클라이언트, 포트, 문자열,...

 

2. 어떤 원리이고 흐름인가?

 

보통 웹사이트 들어갈 때 어떻게 들어가는가?

브라우저 위에 주소창에 URL을 쓰고 들어간다. 그러면 브라우저가 그 URL(서버)로 연결시켜준다.

서버에서 받아온 데이터들을 브라우저가 받아서 파싱해서 뿌려준다.

 

이게 보통 웹의 흐름이라면,



AJAXAJAX 자체가 브라우저라고 생각하면 된다

URL을 받고, AJAX 내부에서 XMLHttpRequest 통신을 해서 URL(서버)로 연결시켜준다.

서버에서 받아온 데이터들을 AJAX가 받는다.  (어떻게 뿌릴지는 여기서 직접 알아서 한다 ㅋㅋ)

 

 

 

<메소드>

기본

$.ajax(settings)

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

 

$(document).ready(function() {

$.ajax({

           type:"GET",

           url:"/test",

           dataType:"JSON", // 옵션이므로 JSON으로 받을게 아니면 안써도 됨

           success : function(data) {

                 // 통신이 성공적으로 이루어졌을 때 이 함수를 타게 된다.

                 // TODO

           },

           complete : function(data) {

                 // 통신이 실패했어도 완료가 되었을 때 이 함수를 타게 된다.

                 // TODO

           },

           error : function(xhr, status, error) {

                 alert("에러발생");

           },

timeout : 5000

     });

});

</script>

 

보조

3. 보조 메서드   625p

 . $("form태그").serialize()
    : form
태그내의 모든 입력필드들의 name 속성을 이용해서
     
파라미터 형식의 문자열을 생성함.
 
폼테그를 선택하면 모든 입력필드를 폼데이터형식으로 만들어 준다.
 
왜 유용한가
 
입력값이 많을 경우 사용하면 좋다.
 
, 반드시 input 필드의 name속성을 이용한다.
 <input type=text" name="aaa".../>


 
. $("form태그").serializeArray()
    : form
태그내의 모든 입력필드들의 name 속성을 이용해서
     
파라미터 정보를 포함한 JS 배열 객체를 생성
 
위와 비슷한데 만들어지는 형식이
 [
  {name:.., tel:.. },
  {name:.., tel:.. },
  {name:.., tel:.. }
 ]


 
. $.param(obj)
    : JS
객체를 파라미터 형식의 문자열로 변환
 form data
형식으로 문자를 만들어 냄.
 

  * 파라미터 형식의 문자열?   name=john&tel=010-222-3333

[출처] [jQuery] Ajax|작성자 별걸

$.get()  $.post() success만 넘기기 때문에 timeout을 지정할 수 없다!!!!!!<

[출처] [jQuery] Ajax|작성자 별걸