jQuery入门——注册事件
下面举例介绍注册事件的几种方法:
以光棒效果为例
1.bind注册:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 <style type="text/css"> 7 .hover{ 8 background: #e8e8e8; 9 } 10 </style> 11 <script type="text/javascript" src="../js/jquery-3.2.1.js"></script> 12 <script type="text/javascript"> 13 $(document).ready(function(){ 14 $('li').bind({ 15 mouseover:function(){ 16 $(this).css('background','#e8e8e8') 17 }, 18 mouseout:function(){ 19 $(this).css('background','') 20 } 21 }) 22 //j卸载事件 23 //$('li').unbind('mouseover mouseout') 24 }); 25 </script> 26 </head> 27 <body> 28 <ul> 29 <li>第一个光棒</li> 30 <li>第二个光棒</li> 31 <li>第三个光棒</li> 32 </ul> 33 </body> 34 </html>
2.on注册:
1 $(document).ready(function(){ 2 $('li').on({ 3 mouseover:function(){ 4 $(this).css('background','#e8e8e8') 5 }, 6 mouseout:function(){ 7 $(this).css('background','') 8 } 9 }) 10 //$('li').off() 11 });
3.使用.hover模仿悬停事件:
1 $(document).ready(function(){ 2 var handlerInOut = function(){ 3 $(this).toggleClass('hover'); 4 } 5 //以下两种写法效果相同 6 //$('li').on( "mouseover mouseout", handlerInOut); 7 $('li').hover(handlerInOut) 8 });