jQuery 이벤트

이벤트 연결

blur focus focusin focusout load
resize scroll unload click dblclick
mousedown mouseup mousemove mouseover mouseout
mouseneter mouseleave change select submit
keydown keypress keyup error ready

이 세상에 이벤트의 종류는 너무나도 많다.
근데 이걸 다 내면 분명히 선생님도 힘들고 우리도 힘들다. 그래서 몇개만 보기로 하자.

이벤트 연결은 .bind()를 다음과 같은 형태로 사용한다.

  • $(selector).bind(eventname, function(){ });
  • $(selector).bind(object);

예제

<input type="text"><br>
$('input').bind('focusin', function() {
  $(this).css('background-color', 'yellow');
});

$('input').bind('focusout', function() {
  $(this).css('background-color', 'white');
});

$(this)는 이벤트를 당하는 녀석 정도로 생각하면 될것 같다.
여기서는 $(this) == $('input')

뭐, 굳이 저렇게 안쓰고 이렇게 쓰는 방법도 있다.

$('input').bind({
  focusin: function() {
    $(this).css('background-color', 'yellow');
  },
  focusout: function() {
    $(this).css('background-color', 'white');
  }
});

이벤트 연결 해지

.unbind()를 사용하면 된다. 이놈도 다양한 사용법이 있다.

  • $(selector).unbind(); //객체의 모든 이벤트 제거
  • $(selector).unbind(eventname); //객체의 특정 이벤트 관련된 모든걸 제거
  • $(selector).unbind(eventname, function); //객체의 특정 이벤트 중 특정한 녀석만 제거

일회용 이벤트 연결

$('div').one('click', function() {
  alert("오늘만 산다!!");
});

context의 활용

예를 들어 이런 코드가 있다고 하자.

<h2>header-0</h2>
<h2>header-1</h2>
$(document).ready(function() {
  $('div').click(function() {
    $('h2').css('color', 'red');
  });
});

앞에 내용을 잘 이해했다면 h2를 눌렀을때 모든 h2의 색깔이 빨간색으로 변한다는 것을 알게 될 것이다. 그러면, 누른 녀석만 빨갛게 하려면?

$('h2').css('color', 'red');

위의 부분을 아래처럼 바꿔주면 된다.

$('h2', this).css('color', 'red');

이벤트 강제 발생

내가 안해도 강제로 이벤트가 발생되게 만드는 방법이 있다.
trigger()라는 메소드를 사용하면 된다. 우리에게 프로 도박꾼의 가능성을 준 경마장 코드로 복습해보자.

<h2>0번말</h2>
<h2>1번말</h2>
<h2>2번말</h2>
$('h2').click(function() { //h2 클릭시 실행되는 메소드
  $(this).append("*");
});

var interval = setInterval(function() {
  var r = Math.random(); //난수 생성
  r = Math.floor(r * $('h2').length); // 0~h2 개수까지
  $('h2').eq(r).trigger('click'); //r번째 말에 대해 click 메소드 강제 실행
}, 250); //0.25초 마다

results matching ""

    No results matching ""