jQuery入门——注册事件

时间:2024-09-02 15:36:02

下面举例介绍注册事件的几种方法:

以光棒效果为例

1.bind注册:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.hover{
background: #e8e8e8;
}
</style>
<script type="text/javascript" src="../js/jquery-3.2.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('li').bind({
mouseover:function(){
$(this).css('background','#e8e8e8')
},
mouseout:function(){
$(this).css('background','')
}
})
//j卸载事件
//$('li').unbind('mouseover mouseout')
});
</script>
</head>
<body>
<ul>
<li>第一个光棒</li>
<li>第二个光棒</li>
<li>第三个光棒</li>
</ul>
</body>
</html>

2.on注册:

 $(document).ready(function(){
$('li').on({
mouseover:function(){
$(this).css('background','#e8e8e8')
},
mouseout:function(){
$(this).css('background','')
}
})
//$('li').off()
});

3.使用.hover模仿悬停事件:

 $(document).ready(function(){
var handlerInOut = function(){
$(this).toggleClass('hover');
}
//以下两种写法效果相同
//$('li').on( "mouseover mouseout", handlerInOut);
$('li').hover(handlerInOut)
});