이벤트 연결시키는 방법
① bind함수
이벤트를 트리거로 함수가 호출될 수 있도록 도와주는 함수
여러 이벤트를 연결하여 사용할 수 있다
<script>
$(function(){
//(1)
$('a').bind('click',function (){
alert('클릭이벤트1')
return false
})
//(2)
$('a').bind('click',function (event){
alert('클릭이벤트2')
event.preventDefault()
})
})
</script>
-> (1),(2) : a태그에 대해 click 이벤트가 발생하면 alert가 실행되고 본래 a태그의 기능은 비활성화 된다
이렇게 본 기능을 비활성화 시키는 방법으로는 함수 끝에 return false 혹은 event.preventDefault() 를 적어주면 된다
<script>
$(function(){
$('img').bind({
mouseout:function(){
$('img').attr('src','../apple.jpg')
},
mouseover:function(){
$('img').attr('src','../banana.jpg')
},
click:function(){
alert('click 이벤트 발생')
}
})
})
</script>
-> img태그에 대하여 mouseout이벤트, mouseover이벤트, click이벤트가 발생하면 각각의 함수가 실행된다
② 선택자에 직접 이벤트를 연결
형식) $('selector').이벤트명(function(){...})
<script>
$(function(){
$('a').click(function(){
$(this).toggleClass('blue')
})
})
</script>
-> a태그에 대하여 click 이벤트가 발생하면 해당 a태그에 blue 클래스가 추가되거나 삭제된다
*toggleClass()는 addClass()와 removeClass()를 번갈아 실행시켜주는 함수이다
'jQuery' 카테고리의 다른 글
[jQuery]wrap, show, hide 함수 / change, focus, blur, submit 이벤트 (0) | 2021.03.09 |
---|---|
[jQuery]romove, empty, one, unbind, hover 함수/ keyup이벤트 (0) | 2021.03.09 |
[jQuery]$.extend, $.each (0) | 2021.03.08 |
[jQuery]addClass, removeClass, toggleClass, filter, is, append, prepend, after, before 함수 (0) | 2021.03.08 |
[jQuery]setTimeout, setInterval, 태그의 인덱스 번호에 따라 구분하기 (0) | 2021.03.05 |