제이쿼리 1 jQuery

[jQuery]
# 글을 쓰는 문장이라고 생각
# 문장의 첫머리는 항상 주어임을 상기
# 주어는 선택자(셀렉터),
  동사는 이벤트,
  목적어는 style, dom, ajax
# 제이쿼리 플러그인
 - 공식 플러그인 : jQuery UI, jQuey Mobile

# 팩토리함수 -> $()
 - jQuery 객체를 생성하기 위한 것
 - 제이쿼리 함수를 사용하기 위해 제이쿼리 객체를 생성한다.

# $(document).ready();
 - window.onload 와는 다름, 온로드는 이미지나 이런거 까지 다 읽어온것
 - ready는 문서구조만 읽어온것


# $(document).ready(function() {  });
    이렇게 줄여 쓸 수 있다.
  => $(function() {  });

1
2
3
4
5
6
7
//$(document).ready(function() {
//  $('.poem-stanza').addClass('highlight');
//});
 
$(function() {
  $('.poem-stanza').addClass('highlight');
});
cs


#  $('선택자').addClass('css');
 - css 추가

1
2
3
$(function() {
  $('#selected-plays>li').addClass('horizontal');
});
cs

# 선택자
셀렉터예시설명
id, class, tag로 선택 ★★★
*$("*")모든 요소들
#id$("#lastname")id가 "lastname"인 요소
.class$(".intro")클래스가 "intro"인 요소들
.class,.class$(".intro,.demo")클래스가 "intro" 또는 "demo"인 요소들
element$("p")<p> 요소들
el1,el2,el3$("h1,div,p")<h1>, <div> and <p> 요소들
처음, 마지막, 홀수, 짝수 선택 ★
 :first$("p:first")첫번째 <p> 요소
 :last$("p:last")마지막 <p> 요소
 :odd$("tr:odd")홀수번째 <tr> 요소들
 :even$("tr:even")짝수번째 <tr> 요소들
자식, 타입에 따른 선택
 :first-child$("p:first-child")All <p> elements that are the first child of their parent
 :first-of-type$("p:first-of-type")All <p> elements that are the first <p> element of their parent
 :last-child$("p:last-child")All <p> elements that are the last child of their parent
 :last-of-type$("p:last-of-type")All <p> elements that are the last <p> element of their parent
:nth-child(n)$("p:nth-child(2)")All <p> elements that are the 2nd child of their parent
 :nth-last-child(n)$("p:nth-last-child(2)")All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n)$("p:nth-of-type(2)")All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n)$("p:nth-last-of-type(2)")All <p> elements that are the 2nd <p> element of their parent, counting from the last child
 :only-child$("p:only-child")All <p> elements that are the only child of their parent
 :only-of-type$("p:only-of-type")All <p> elements that are the only child, of its type, of their parent
태그간 관계에 따른 선택
parent > child$("div > p")All <p> elements that are a direct child of a <div> element
parent descendant$("div p")All <p> elements that are descendants of a <div> element
element + next$("div + p")The <p> element that are next to each <div> elements
element ~ siblings$("div ~ p")All <p> elements that are siblings of a <div> element
비교에 따른 선택
 :eq(index)$("ul li:eq(3)")The fourth element in a list (index starts at 0)
 :gt(no)$("ul li:gt(3)")List elements with an index greater than 3
 :lt(no)$("ul li:lt(3)")List elements with an index less than 3
 :not(selector)$("input:not(:empty)")All input elements that are not empty
태그 등에 따른 선택
 :header$(":header")All header elements <h1>, <h2> ...
 :animated$(":animated")All animated elements
 :focus$(":focus")The element that currently has focus
 :contains(text)$(":contains('Hello')")All elements which contains the text "Hello"
 :has(selector)$("div:has(p)")All <div> elements that have a <p> element
 :empty$(":empty")All elements that are empty
 :parent$(":parent")All elements that are a parent of another element
 :hidden$("p:hidden")All hidden <p> elements
 :visible$("table:visible")All visible tables
 :root$(":root")The document’s root element
 :lang(language)$("p:lang(de)")All <p> elements with a lang attribute value starting with "de"
attribute에 따른 선택
[attribute]$("[href]")All elements with a href attribute
[attribute=value]$("[href='default.htm']")All elements with a href attribute value equal to "default.htm"
[attribute!=value]$("[href!='default.htm']")All elements with a href attribute value not equal to "default.htm"
[attribute$=value]$("[href$='.jpg']")All elements with a href attribute value ending with ".jpg"
[attribute|=value]$("[title|='Tomorrow']")All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value]$("[title^='Tom']")All elements with a title attribute value starting with "Tom"
[attribute~=value]$("[title~='hello']")All elements with a title attribute value containing the word "hello"
[attribute*=value]$("[title*='hello']")All elements with a title attribute value containing the string "hello"
input 태그 선택 ★
 :input$(":input")모든 input 요소들
 :text$(":text")타입이 "text"인 input 요소들 ★★
 :password$(":password")타입이 "password"인 input 요소들
 :radio$(":radio")타입이 "radio"인 input 요소들
 :checkbox$(":checkbox")타입이 "checkbox"인 input 요소들
 :submit$(":submit")타입이 "submit"인 input 요소들
 :reset$(":reset")타입이 "reset"인 input 요소들
 :button$(":button")타입이 "button"인 input 요소들
 :image$(":image")타입이 "image"인 input 요소들
 :file$(":file")타입이 "file"인 input 요소들
 :enabled$(":enabled")enabled인 input 요소들
 :disabled$(":disabled")disabled인 input 요소들
 :selected$(":selected")selected인 input 요소들
 :checked$(":checked")checked인 input 요소들

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$(function() {
  $('#selected-plays>li').addClass('horizontal');
//  $('li>ul>li').addClass('sub-level');
  $('li:not(.horizontal)').addClass('sub-level');
  
  $('a[href $="pdf"]').addClass('pdflink');
  $('a[href ^="mailto"]').addClass('mailto');
  $('a[href *="henry"]:not(.mailto)').addClass('henrylink');
  
//  $('tr:odd').addClass('alt'); //짝수
//  $('tr:nth-child(odd)').addClass('alt'); //홀수
  $('tr').filter(':odd').addClass('alt'); // filter 함수사용
  
//  $('td:contains("Henry")').addClass('highlight');
//  $('td:contains("Henry")').nextAll().andSelf().addClass('highlight');
//  $('td:contains("Henry")').parent().addClass('highlight');
//  $('td:contains("Henry")').parent().find('td').addClass('highlight');
//  $('td:contains("Henry")').parent().find('td:eq(0)').addClass('highlight'); //  첫번째 td
  $('td:contains("Henry")').parent().find('td:eq(0)').addClass('highlight')
                           .end().find('td:eq(1)').addClass('highlight'); // 첫번째, 두번째 td
 
});
cs


# each !! (중요)
 - jQuery로 배열을 관리할 때는 each() 메서드를 사용

 - 1) $.each(object, function(index, item) {})
  - Ajax에서 json형태로 콜백함수에 많이 사용

 - 2) $(selector.each(function(index, item) {})
  - 태그를 순회하며 각각 다른 작업을 해주어야 할 때

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.high-light-0{background: yellow;}
.high-light-1{background: orange;}
.high-light-2{background: blue;}
.high-light-3{background: green;}
.high-light-4{background: red;}
</style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function() {
    //- 1) $.each(object, function(index, item) {})
    //- Ajax에서 json형태로 콜백함수에 많이 사용
    
      var array = [
        {name'Hanbit', link: 'http://hanbit.co.kr'},
        {name'Naver', link: 'http://naver.co.kr'},
        {name'Daum', link: 'http://daum.net'}
      ];
  
      $.each(array, function(index, item) {
      var output = '';
 
      output += '<a href="' + item.link + '">';
      output += '<h1>' + item.name + '</h1>';
      output += '</a>';
 
      document.body.innerHTML += output;
 
    });
      
    // - 2) $(selector.each(function(index, item) {})
    // - 태그를 순회하며 각각 다른 작업을 해주어야 할 때

    $('h1').each(function (index,item) {
      $(item).addClass('high-light-'+index);
    });
  });
    
</script>
</head>
<body>
 <h1>item - 0</h1>
 <h1>item - 1</h1>
 <h1>item - 2</h1>
 <h1>item - 3</h1>
 <h1>item - 4</h1>
</body>
</html>
cs



# 이벤트
 - 이벤트 핸들러를 할당할 수 있는 통합 메서드를 제공
 - 핸들러의 매개변수로 사용할 수 잇는 Event읶스턴스 제공

 - on() : 통합함수, 첫번째 인자는 이벤트이름, 두번째 이벤트객체
 - 핸들러 함수 : 개별함수
 - off() : 이벤트 제거
 - one() : 일회용 이벤트
 - trigger : 다른 이벤트를 강제적으로 실행 시킬 수 있다.
 - toggle : 번갈아 실행 할 수 있는 함수들


# step01
large 클릭시 large스타일 적용

1
2
3
4
5
$(function() {
  $('#switcher-large').on('click'function() {
    $('body').addClass('large');
  });
});
cs


# step02
버튼마다 스타일 적용 및 해지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(function() {
  $('#switcher-large').on('click'function() {
    $('body').addClass('large');
    $('body').removeClass('narrow');
  });
  $('#switcher-narrow').on('click',function(){
    $('body').addClass('narrow');
    $('body').removeClass('large');
  });
  $('#switcher-default').on('click',function(){
    $('body').removeClass('large');
    $('body').removeClass('narrow');
  });
});
cs


#step03
클릭한 버튼만 selected 스타일이 적용 되도록

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(function() {
  $('#switcher-default').removeClass('selected');
  
  $('#switcher-large').on('click'function() {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass('narrow').addClass('large');
  });
  $('#switcher-narrow').on('click'function() {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass('large').addClass('narrow');
  });
  $('#switcher-default').on('click',function(){
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass('large','narrow');
  });
});
cs


#step04
중복된 코드를 최소화 하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(function() {
  $('#switcher-default').removeClass('selected');
 
  $('#switcher-large').on('click'function() {
    $('body').removeClass('narrow').addClass('large');
  });
  $('#switcher-narrow').on('click'function() {
    $('body').removeClass('large').addClass('narrow');
  });
  $('#switcher-default').on('click'function() {
    $('body').removeClass('large''narrow');
  });
  //묶음
  $('#switcher .button').on('click'function() {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
  });
});
cs


#step05
중복된 코드를 더 최소화 하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(function() {
  $('#switcher .button').on('click'function() {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass();
  });
  
  $('#switcher-large').on('click'function() {
    $('body').addClass('large');
  });
  $('#switcher-narrow').on('click'function() {
    $('body').addClass('narrow');
  });
});
cs


#step06
$('#switcher .button') => 모두포함 => id구별

1
2
3
4
5
6
7
8
9
10
11
12
13
$(function() {
  $('#switcher .button').on('click'function() {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass();
    
    if(this.id=='switcher-large'){
      $('body').addClass('large');
    } else if (this.id=='switcher-narrow'){
      $('body').addClass('narrow');
    }
  });
});
cs


#step07
on() => click()로 변경

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(function() {
// $('#switcher .button').on('click', function() {
    $('#switcher .button').click(function(){
 
        $('.button').removeClass('selected');
        $(this).addClass('selected');
        $('body').removeClass();
 
        if (this.id == 'switcher-large') {
          $('body').addClass('large');
        } else if (this.id == 'switcher-narrow') {
          $('body').addClass('narrow');
        }
    });
});
cs


#step08
hover 사용

1
2
3
4
5
6
7
$(function() {
  $('#switcher .button').hover(function(){
    $(this).addClass('hover');
  },function(){
    $(this).removeClass('hover');
  });
});
cs


#step09
switcher => h3 클릭 => 버튼 3개 화면에서 사라지게 하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(function() {
  $('#switcher h3').click(function() {
    $('#switcher .button').toggleClass('hidden');
  });
  
  $('#switcher .button').click(function(){
    
      $('.button').removeClass('selected');
      $(this).addClass('selected');
      $('body').removeClass();
 
      if (this.id == 'switcher-large') {
        $('body').addClass('large');
      } else if (this.id == 'switcher-narrow') {
        $('body').addClass('narrow');
      }
  });
});
cs


#step10
바깥쪽 클릭시에도 동작 및 이벤트 버블링 방지

# 이벤트 버블링 방지
 - click(function(event){ => 이벤트 객체 인자를 추가 (이름 임의 지정)
 - event.stopPropagation(); 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(function() {
  $('#switcher').click(function() {
    $('#switcher .button').toggleClass('hidden');
  });
 
  $('#switcher .button').click(function(event) {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass();
 
    if (this.id == 'switcher-large') {
      $('body').addClass('large');
    } else if (this.id == 'switcher-narrow') {
      $('body').addClass('narrow');
    }
    
    event.stopPropagation();
  });
});
cs



G
M
T
음성 기능은 200자로 제한됨
G
M
T
음성 기능은 200자로 제한됨
G
M
T
음성 기능은 200자로 제한됨

G
M
T
음성 기능은 200자로 제한됨

#step11
on() : 통합 이벤트 발생, off() : 이벤트 해제
narrow, large 버튼을 클릭 후 버튼이 사라지는 이벤트를 해제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$(function() {
  $('#switcher').on('click'function() {
    $('#switcher .button').toggleClass('hidden');
  });
 
  $('#switcher .button').click(function(event) {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass();
 
    if (this.id == 'switcher-large') {
      $('body').addClass('large');
    } else if (this.id == 'switcher-narrow') {
      $('body').addClass('narrow');
    }
 
    event.stopPropagation();
  });
 
  $('#switcher-large,#switcher-narrow').click(function() {
    $('#switcher').off('click');
  });
});
cs


#step12
네임스페이스 'click.A'
트리거 - 클릭 되있는 것 처럼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(function() {
  function a() {
    $('#switcher .button').toggleClass('hidden');
  }
  $('#switcher').on('click.A', a);
 
  $('#switcher .button').click(function(event) {
    $('.button').removeClass('selected');
    $(this).addClass('selected');
    $('body').removeClass();
 
    if (this.id == 'switcher-large') {
      $('body').addClass('large');
      $('#switcher').off('click.A');
    } else if (this.id == 'switcher-narrow') {
      $('body').addClass('narrow');
      $('#switcher').off('click.A');
    } else {
      $('#switcher').on('click.A', a);
    }
 
    event.stopPropagation();
  });
 
  $('#switcher').trigger('click.A'); // 이벤트 강제 발생
});
cs





덧글

댓글 입력 영역