LostCatBox

Html-JQuery

Word count: 2.3kReading time: 14 min
2023/02/05 Share

참조

https://poiemaweb.com/jquery-basics

보기좋은정리

자세한것

왜?

회사에서 활용하는것이므로 시작하게 되었다.

소개

jQuery는 존 레식이 2006년에 발표한 크로스 플랫폼을 지원하는 경량의 자바스크립트 라이브러리이다. HTML 문서의 탐색이나 조작, 이벤트 핸들링, 애니메이션, Ajax등을 멀티 브라우저를 지원하는 API를 통해 더욱 간편하게 사용할 수 있다.

  • 크로스 플랫폼을 지원하는 jQuery는 어떠한 브라우저에서도 동일하게 동작한다. 이것은 브라우저 호환성을 고려하여 대체 코드(Polyfill)를 작성할 필요가 없다는 것을 의미한다.

  • 네이티브 DOM API(DOM Query, Traversing, Manipulation 등)보다 직관적이고 편리한 API를 제공한다. CSS 스타일의 selector를 사용할 수 있으며 조작 또한 강력하며 유연하다.

  • 이벤트 처리, Ajax, Animation 효과를 쉽게 사용할 수 있다.

  • 다양한 플러그인이 존재하며 다른 라이브러리들과 충돌을 일으키지 않는다.

현재 Jquery3.0이 릴리스 되었다.

모든 브라우저는 HTML 문서를 로드할 때 DOM(문서 객체 모델: Document Object Model)을 생성한다. DOM은 HTML과 XML 문서를 위한 API로 웹페이지의 각 요소에 접근하고 수정하는 방법을 제시한다. DOM은 객체의 트리로 구성되는데 이러한 구조를 DOM tree라 한다.

jquery 시작

jquery를 사용하기위해서는 먼저 query 객체를 생성하여야 한다.

jquery객체를 생성하기위해서는 jQuery 함수를 사용한다.

1
2
3
jQuery()

$()

함수에 전달되는 인수의 종류에 따라 다른 움직임을 하지만 결국 jQuery객체를 반환한다.

jQuery() 함수에 의해 생성된 객체를 Matched set 또는 jQuery selection이라 한다. 이 객체에는 선택한 요소에 대한 참조가 저장되어 있는데 선택된 요소는 1개일수도, 여러 개일 수도 있다. jQuery가 제공하는 프로퍼티와 메소드는 prototype 객체를 통해 접근할 수 있다.

jQuery 함수에 전달되는 인수의 종류에 따라

CSS 스타일의 selector를 인수로 전달받을 때

jQuery는 CSS 스타일의 selector를 이용하여 요소를 선택

jQuery() 함수는 선택자에 의해 선택된 요소들을 jQuery 객체를 반환한다

1
$('h1');

HTML을 인수로 전달받을 때

HTML 문자열을 인수로 받으면 새로운 HTML 요소를 생성한다.

1
$('<p id="test">My <em>new</em> text</p>').appendTo('body');

JavaScript 객체를 인수로 전달받을 때

JavaScript 객체(plain object, DOM element, array 등)를 인수로 받으면 그 객체를 jQuery 객체로 wrap한 객체를 반환한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Define a plain object
var foo = { foo: 'bar', hello: 'world' };

// Pass it to the jQuery function
var $foo = $(foo);

// Accessing property values
var test1 = $foo.prop('foo');
console.log(test1); // bar

// Setting property values
$foo.prop('foo', 'foobar');

// Accessing property values
var test2 = $foo.prop('foo');
console.log(test2); // foobar

$(document).ready(function(){})

1
2
3
4
5
6
7
jQuery(document).ready(function(){
// process..
});

$(document).ready(function(){
// process..
});

$(document).ready(callback 함수) = jQuery와 $는 같은 의미이다
document가 준비된 시점에 (=메모리에 로딩 시에) 익명함수가 실행되고,
이 익명함수는 현 페이지에서 필요한 이벤트 행위를 일괄적으로 등록한다.

  • jQuery 이벤트 메서드 중 하나
    • 문서의 DOM 요소들을 조작 할 수 있는 시점에서 호출
    • javascript의 load 이벤트와 비슷

jQuery 기분 문법 -Selector (선택자)

  • $(‘a’) – page 내 모든
  • $(‘div a’) – page 내
  • $(‘#test’) – id가 test인 태그
  • $(‘.btn’) – class가 btn인 모든 태그
  • $(‘tr:odd’) - 태그들 중 홀수번째들
  • $(‘tr:last tr:last’) – 문서내의 마지막
  • $(‘b:contains(‘hi’)) – hi를 content로 가진 b태그
  • $(‘div:has(‘ul’) -
      을 가진
      태그
    • $(‘input:checkbox’) – input태그중 checkbox
    • $(‘td nth-child(2n)’) –2의 배수 번째

    Content/DOM 변경 및 조회 메소드

    • html()
      – 선택요소의 html 내용을 가져옴. innerHTML과 동일
    • html(value)
      – 선택요소에 인수로 받은 value를 넣는다.
      – value내에 html태그가 있는 경우 태그로 들어간다.
    • text()
      – 선택요소 내의 html태그 요소를 제외한 내용을 가져옴.
      innerText innerText와 동일.
    • text(value)
      – 선택요소 내에 인수로 받은 value를 넣는다.
      – value내의 html태그도 text로 들어간다.
    • val()
      – input 태그의 value 값을 조회
    • val(value)
      – 인수로 받은 value를 input 태그의 value 값을 설정

    사용예제

    jquery ready 와 이벤트 등록 기본

    • $(“tag“)로 이벤트 등록
    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
    <html>
    <head>
    <meta charset="UTF-8">
    <title>jQuery basic</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    //jQuery의 ready함수는 document가 준비되는 시점에 실행된다.
    /* jQuery(document).ready(function() {
    alert("jquery");
    }); */
    // jQuery와 $는 같은 표현이다
    $(document).ready(function() {
    //alert("jquery"+ document.getElementById("ts"));

    //ready 시점에 현 페이지의 이벤트를 등록한다.
    // 이벤트 : a tag를 클릭했을 때, 자신의 텍스트를 alert
    $("a").click(function () {
    alert($(this).text());
    })
    });
    </script>
    </head>
    <body>
    <div class="container">
    <h3>jQuery Basic</h3> <br>
    <span id="ts">test span</span>

    <ul>
    <li><a href="#">test1</a>
    <li><a href="#">test2</a>
    <li><a href="#">test3</a>
    </ul>
    <!-- <script type="text/javascript">
    alert(document.getElementById("ts"));
    </script>
    -->
    </div>
    </body>
    </html>

    jQuery ready & 이벤트 등록 기본 - Input

    • $(“:type“)로 이벤트 등록
    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
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>jQuery Basic</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    //document가 준비된 시점에 (=메모리에 로딩 시에) 익명함수가 실행되고,
    //이 익명함수는 현 페이지에서 필요한 이벤트 행위를 일괄적으로 등록한다.
    $(document).ready(function() {
    //이번트 등록
    // : $(:button) -> jQuery 필터로 선택, type=button을 선택한다.
    $(":button").click(function() {
    alert($(this).val() + "번이 클릭했다!");
    });
    });
    </script>
    </head>
    <body>
    <div class="container">
    <input type="button" value="버튼 1"><br>
    <input type="button" value="버튼 2"><br>
    <input type="button" value="버튼 3"><br>
    </div>
    </body>
    </html>

    3. Class Seletor 이용 + Confirm 적용

    • $(“.class“)로 이벤트 등록
      • 다음과 네이버는 이벤트 적용이 되고, 구글은 바로 이동이된다.
    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
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script>
    $(document).ready(function() {
    $(".ct").click(function () {
    //alert("클릭");

    //취소누르면 return
    return confirm($(this).text()+" 이동하시겠습니까?");
    });
    });
    </script>
    </head>
    <body>
    <div class="container">
    <a href="http://daum.net" class="ct">다음넷으로</a><br>
    <a href="http://naver.com" class="ct">네이버로</a><br>
    <a href="http://google.com">구글로</a><br>
    </div>
    </body>
    </html>

    4. 특정대상 골라서 event 주기 - id

    • $(“#id“)로 이벤트 등록

    text 적용 시

    $(“#id”).text($(this).val());

    html tag 적용 시

    $(“#id”).html(““ + $(this).val() + “</html tag>”);

    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
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>jQuery Basic</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    //id가 btn2인 대상을 선택해서, 이벤트 적용
    $("#btn2").click(function() {
    alert($(this).val());
    });

    //id가 btn3인 대상을 선택해서, 이벤트 적용
    // : 자신의 value를 <span id="resultView"> 영역에 출력
    $("#btn3").click(function() {
    //alert($(this).val());
    //$("#resultView").text($(this).val());

    //innerHTML 형식으로 html tag 적용 : html()
    $("#resultView").html("<font color=blue>"+ $(this).val() + "</font>");
    });
    });
    </script>
    </head>
    <body>
    <div class="container">
    <br><br>
    <input type="button" value="Test 1: 이벤트 적용 X"><br><br>
    <input type="button" value="Test 2: 값(value) 출력" id="btn2"><br><br>
    <input type="button" value="Test 3: 값(value)를 span에 출력" id="btn3"> :

    <span id="resultView">span 영역</span>
    </div>
    </body>
    </html>

    5. class tag Selector 적용

    • $(“.class tag“)로 이벤트 등록

    class = food의 li tag 에만 이벤트 적용

    food class에 속하는 li를 클릭했을 때만, alert 반응이 있다.

    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">
    <style type="text/css">
    .a{
    background-color: yellow;
    }

    .b{
    background-color: lime;
    }
    </style>
    <title>jQuery CSS 선택</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

    // food class 이하의 li 태그들을 대상으로
    // 이벤트를 적용
    $(".food li").click(function() {
    alert($(this).text());
    });

    });
    </script>
    </head>
    <body>
    <div class="container">
    <ol class="a food">
    <li>바나나</li>
    <li>사과</li>
    <li>포도</li>
    </ol>

    <ol class="food b">
    <li>요거트</li>
    <li>치즈케이크</li>
    <li>크림치즈</li>
    </ol>

    <ol>
    <li>LA</li>
    <li>New York</li>
    <li>Washington</li>
    </ol>
    </div>
    </body>
    </html>

    6. Selector 대상이 여러 개일 경우

    $(“selector, selector .. “)로 이벤트 등록 (이벤트 조건을 여러개 등록가능하다)

    1. id가 “testBtn”일 경우, 클릭하면 자신의 value를 alert으로 출력

    2. class가 “student”인 경우, 클릭하면 id가 result인 영역에 자신의 text 출력

    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
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {

    //1. id가 testBtn일 경우, 클릭하면 자신의 value를 alert으로 출력
    $("#testBtn").click(function() {
    alert($(this).val());
    });

    //2. class가 "student"인 경우, 클릭하면 id가 result인 영역에 자신의 text 출력
    // 셀렉터를 , 로 이어서 둘 다 출력되도록 함
    $(".student, .teacher").click(function() {
    //alert($(this).text());
    $("#result").html("<font color=blue>"+ $(this).text()+ "</font>");
    });

    });
    </script>
    </head>
    <body>
    <div class="container">
    <input type="button" value="selector 연습 1" id="testBtn"><br><br>

    <div class="student">파프리카</div>
    <div class="teacher">오렌지</div>
    <div class="student">자몽</div><br>
    <hr>
    <div id="result"></div>
    </div>
    </body>
    </html>

    7. 이미지 조정

    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
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    //사진 감추기
    $("#hideBtn").click(function() {
    //hide(시간, 후속작업)
    $("#imgView").hide(2000, function() {
    $("#stateInfo").html("<font size=7 color='lime'>"
    +"밀크 없다!"+"</font>");
    });
    });

    //사진 보기
    $("#showBtn").click(function() {
    $("#imgView").show(2000);
    });

    });
    </script>
    </head>
    <body>
    <div class="container">
    <img src="milk.jpg" id="imgView" height="500px" width="400px">
    <input type="button" value="사진 감추기" id="hideBtn">
    <input type="button" value="사진 보기" id="showBtn">

    <hr>

    <span id="stateInfo">
    <font size="7" color="green">밀크 있다!</font>
    </span>
    </div>
    </body>
    </html>
CATALOG
  1. 1. 참조
  2. 2. 왜?
  3. 3. 소개
  4. 4. jquery 시작
    1. 4.1. jQuery 함수에 전달되는 인수의 종류에 따라
      1. 4.1.1. CSS 스타일의 selector를 인수로 전달받을 때
      2. 4.1.2. HTML을 인수로 전달받을 때
      3. 4.1.3. JavaScript 객체를 인수로 전달받을 때
    2. 4.2. $(document).ready(function(){})
    3. 4.3. jQuery 기분 문법 -Selector (선택자)
    4. 4.4. Content/DOM 변경 및 조회 메소드
  5. 5. 사용예제
    1. 5.1. jquery ready 와 이벤트 등록 기본
    2. 5.2. jQuery ready & 이벤트 등록 기본 - Input
    3. 5.3. 3. Class Seletor 이용 + Confirm 적용
    4. 5.4. 4. 특정대상 골라서 event 주기 - id
      1. 5.4.1. text 적용 시
      2. 5.4.2. html tag 적용 시
    5. 5.5. 5. class tag Selector 적용
    6. 5.6. 6. Selector 대상이 여러 개일 경우
    7. 5.7. 7. 이미지 조정