$(document).ready(function() {
$(selector).이벤트메소드(function (event) { ... });
});
<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("h1").click(function () {
alert("클릭");
});
});
</script>
<h3>이벤트 연결</h3>
<hr>
<h1>click</h1>
| 실행화면
mouseenter 이벤트와 mouseleave 이벤트를 동시 연결하여 사용해야 한다.
<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("h2").hover(
function () {
$(this).css({
backgroundColor: "pink",
color: "purple",
});
},
function () {
$(this).css({
backgroundColor: "",
color: "",
});
}
);
});
</script>
<h3>이벤트 연결</h3>
<hr>
<h2>hover</h2>
| 실행화면
글자 위에 마우스 커서를 올리면 "pink"로 바뀌고, 내리면 원래의 기본 색으로 돌아온다.
on() 메소드로 이벤트를 연결할 수 있다.
1. 첫 번째 방법 : 이벤트를 문자열로 연결한다.
<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#box").css({
width:100,
height:100,
backgroundColor:"orange",
}).on("click",function(){
$(this).css({
backgroundColor:"purple",
})
}).on("mouseenter", function(){
$(this).css({
backgroundColor:"yellow",
})
}).on("mouseleave", function(){
$(this).css({
backgroundColor:"red",
})
})
})
</script>
<h3>이벤트</h3>
<hr>
<div id="box"></div>
2. 두 번째 방법 : 이벤트를 키값으로 연결한다.
<!-- jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#box")
.css({
width: 200,
height: 200,
backgroundColor: "yellow",
})
.on({
click: function () {
$(this).css({
backgroundColor: "pink",
});
},
mouseenter: function () {
$(this).css({
backgroundColor: "purple",
});
},
mouseleave: function () {
$(this).css({
backgroundColor: "yellow",
});
},
});
});
</script>
<h3>이벤트</h3>
<hr />
<div id="box"></div>
| 실행화면
box를 클릭했을 때 .on (click)
box에서 마우스가 떠났을 때 .on (mouseleave)
++ off() 메소드는 이벤트를 제거할 수 있다.
event.preventDefault()
제거하고 싶은 이벤트에 위 코드를 작성하면 기본 이벤트가 제거된다. 해당하는 그 이벤트만! 제거된다.