jQuery val(), text()에 대해서 알아보겠습니다.


val() text()의 차이는 


input DOM과 같이 value 속성에 값이 적용되는 DOM은 val() 함수를 사용하고
div와 같이 <div></div> 사이에 text가 값이 적용되는 DOM은 text()함수를 사용합니다.


<input type="text" id="ipt" placeholder="입력 후 버튼을 클릭"/>

<div class="test">1번 div</div><br/>


------------------ 값 가져오기 --------------------<br/>

<button id="ipt_btn">input value</button>

<button id="div_test">div text</button><br/><br/>


------------------ 값 셋팅하기 ---------------------<br/>

<button id="set_ipt_btn">input 셋팅</button>

<button id="set_div_test">div 셋팅</button>


- jQuery

$(document).ready(function() {

// 값 가져와서 알림창으로 띄우기

  $('#ipt_btn').off('clcik').on('click', function() {

    alert($('#ipt').val());

    });

    $('#div_test').off('clcik').on('click', function() {

    alert($('.test').text());

    });

 // DOM에 값 셋팅하기

    $('#set_ipt_btn').off('clcik').on('click', function() {

    $('#ipt').val('input 셋팅');

    });

    $('#set_div_test').off('clcik').on('click', function() {

    $('.test').text('div 셋팅');

    });

});


 : 이동


간단하게 val(), text() 함수를 이용하여 DOM의 값을 가져오고

셋팅하는 방법을 알아보았습니다.


다음 시간은 jQuery를 이용하여 CSS를 적용하는 방법에 대해 알아보겠습니다.



jQuery trigger에 대해서 알아보겠습니다.

trigger를 굳이 해석하자면 방아쇠, (어떤) 계기등으로 해석할 수 가 있습니다.

jQuery에서 trigger는 어떤 함수를 실행시켜주는 함수로 보시면 될꺼 같습니다.


<div class="trigger">1번 div</div>

- jQuery

$(document).ready(function() {

   $('.trigger').click(function() {

    var idx = $('. trigger').index(this);

        alert(idx + "번 div, 내용 : " + $(this).text());

   });

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

});

trigger클래스의 클릭 이벤트로 alert창에 간단한 내용이 뜨도록 정의했습니다.

trigger를 작성하지 않았을 때는 trigger 클래스를 가진 DOM을 클릭했을 때 alert창이 떴는데

현재는 trigger를 선언했기 때문에 자동으로 alert창이 뜨는걸 확인할 수 있습니다.


사용자의 입력없이 이벤트를 실행 시킬때 유용하게 사용할 수 있을꺼 같습니다.

click, change, blur, dbclick 등등 다양한 이벤트를 적용할 수 있습니다.


 : 이동


다음 시간은 jquery를 이용하여 input value의 값을 셋팅하고, 값을 가져오는 것과 일반 DOM에 텍스트 값을 반영하는 방법에 대해 알아보겠습니다.



jQuery this에 대해서 알아보겠습니다.

this 즉, 자기자신을 가르키는 변수라고 생각하시면 될꺼 같습니다.

예제를 통해 함께 알아보겠습니다.


<div class="click">1번 div</div>

<div class="click">2번 div</div>

<div class="click">3번 div</div>


지난 시간에는 id를 이용하여 각 DOM 마다 button 클릭 이벤트를 하나씩 설정해줬습니다.

this를 통해서 소스를 깔끔하고 편하게 작성해보겠습니다.

- jQuery

$(document).ready(function() {

   $('.click').click(function() {

    var idx = $('.click').index(this);

        alert(idx + "번 div, 내용 : " + $(this).text());

   });

});


this는 선택된 자기자신을 표현합니다.

1번 DIV가 클릭 됐다면 1번 DIV로 선언된 DOM(<div class="click">1번 div</div>)을 

2번 DIV가 클릭 됐다면 2번 DIV로 선언된 DOM(<div class="click">2번 div</div>)을 

3번 DIV가 클릭 됐다면 1번 DIV로 선언된 DOM(<div class="click">3번 div</div>)을 

나타냅니다.


class 셀렉터를 통해 click 클래스에 클릭 이벤트를 정의했습니다.

index() 함수는 해당 DOM의 순서를 반환합니다. 제일 처음은 0, 1, 2 0번부터 순서대로 증가합니다.


예제 : 이동


this를 통해서 이전과 비교했을 때 코드도 줄고 보기도 편해졌습니다.

this를 활용해서 더 편하고 쉽게 코드를 작성하시기 바랍니다~

다음 시간은 trigger에 대해서 알아보겠습니다.


Jquery 이벤트에 대해서 알아보겠습니다.

1.click() 이벤트

가장 많이 사용하는 click 이벤트입니다.

<div id="click1">1번 div</div>

<div id="click2">2번 div</div>

<div id="click3">3번 div</div>


- jQuery

$(document).ready(function() {

   $('#click1').click(function() {

    alert("1번 div");  

   });

 $('#click2').click(function() {

    alert("2번 div");  

   });

 $('#click3').click(function() {

    alert("3번 div");  

   });

});

# id 선택자 이용하여 click 이벤트가 발생했을 때 알람을 띄우는 간단한 예제를 작성했습니다.

예제 : 이동하기


2. blur() 이벤트

blur 이벤트는 HTML DOM이 포커스를 잃었을 때 발생하는 이벤트입니다.

보통 input DOM에 적용하여 사용합니다.

아이디나 패스워드 입력을 마치고 포커스를 잃었을 때 유효성 검사를 위해 사용하기도 합니다.

<input type="text" id="iptTest"/>

- jQuery

$('#iptTest').blur(function() {

alert("iptTest out");

 });

# id 선택자 이용하여 iptTest가 포커스를 잃었을 때 알람을 띄우는 간단한 예제를 작성했습니다.


예제 : 이동



다음시간에는 jquery 코드를 줄이기 위한 자기 자신을 가르키는 요소 

this를 이용하는 방법을 알아보겠습니다.

this를 이용하면 반복되는 코드도 줄고 간단하게 기능을 구현할 수 있습니다.


class 추가나 삭제는 css에 선언된 class를 이용하여 active 효과를 줄 때 보통 많이 사용합니다.


<div class="test">테스트입니다.</div>

<button class="btn">변경</button>

- css 선언

.test.active {

color:red;

}

위의 선언은 test라는 class를 가진 DOM에 active class가 함께 있으면 color를 red로 변경하라는 선언입니다.

jQuery를 이용하여 class를 추가해 변경되는 모습을 확인해보겠습니다.

- jQuery


$(document).ready(function() {

   $(".btn").off("click").on("click", function() {

// test class를 포함하는 DOM 객체가 active class를 포함하면 true 아니면 false를 반환

       if ($(".test").hasClass("active"))

// active class 제거

            $(".test").removeClass("active");

       }

       else {

// active class 추가

            $(".test").addClass("active");

       }

   });

});


다음 시간에 배울 버튼 클릭 이벤트도 함꼐 포함되어 있지만 이번에는 class가 변경됨에 따라 색상이 변경되는 부분을 확인하시면 될듯합니다.


jQuery hasClass() 함수를 통해 active 를 포함하고 있는지 확인하고

포함하고 있지 않으면 addClass() 함수를 통해 추가하고

포함하고 있으면 removeClass() 함수를 통해 삭제합니다.


예제 : 이동하기



가장 많이 사용되는 id와 class 셀렉터를 먼저 알아보겠습니다.

1. class 셀렉터

<div class="test">class 테스트입니다.</div>
<div id="test">id 테스트입니다.</div>

ex) $( ".text" ).text( "The DOM is now loaded" );

=> 실행 결과

The DOM is now loaded
id 테스트입니다.

* class selector는 앞에 을 붙여서 선택할 수 있습니다.
------------------------------------------------------------------------

2. id 셀렉터

<div class="test">class 테스트입니다.</div>
<div id="test">id 테스트입니다.</div>

ex) $( "#text" ).text( "The DOM is now loaded" );

=> 실행 결과

class 테스트입니다.
The DOM is now loaded

* id selector는 앞에 을 붙여서 선택할 수 있습니다.
------------------------------------------------------------------------

위 두개의 셀렉터를 가장 많이 사용하고 두 개만 이용해도 거의 모든 기능을 다루는데 문제 없이 활용할 수 있습니다.

추가로 jquery 에서 제공하는 다양한 셀럭터들을 맛보기로 몇개만 소개하겠습니다.

1. all selector  ("*")

ex) $("*").css("border", 3px solid red");

-----------------------------------------------------------------------------------------------

2. 속성 prefix 셀렉터 [name|=”value”]

<a href="example.html" hreflang="en">Some text</a>
<a href="example.html" hreflang="en-UK">Some other text</a>
<a href="example.html" hreflang="english">will not be outlined</a>


ex) $( "a[hreflang|='en']" ).css( "border", "3px dotted green" );


=> 실행 결과

Some text Some other text will not be outlined

-----------------------------------------------------------------------------------------------

3. 문자를 포함하는 셀렉터  [name*=”value”]

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">

ex) $( "input[name*='man']" ).val( "has man in it!" );

=> 실행 결과

   

-----------------------------------------------------------------------------------------------

4. 단어를 포함하는 셀렉터  [name~=”value”]

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">

ex) $( "input[name*='man']" ).val( "mr. man is in it!" );

=> 실행 결과

   

-----------------------------------------------------------------------------------------------


jquery 셀렉터에 대해 간략하게 소개하였습니다~

다음 강의에서 만나요~


+ More jQuery

 - [jQeury] jquery this, 코드 줄이기, jquery index, 인덱스

 - [jQuery] - jQeury] val(), text() 값 셋팅, 값 가져오기 setValue, setText

 - [jQuery] - [jQeury] jquery 클래스 추가(addClass), class 추가 삭제(removeClass) 및 확인(hasClass)

 - [jQuery] - [jQeury] jquery tigger, jquery 함수 실행, 이벤트 실행

 - [jQuery] - [jQeury] jQuery css, jQuery 스타일 적용


+ Recent posts