jQuery事件綁定
事件綁定
jquery事件的簡單操作:
$().事件類型(function事件處理);
$().事件類型();
1 . jquery事件綁定
#$().bind(事件類型,function事件處理);
$ ().bind(類型1?類型2?類型3,事件處理); ??//給予許多不同類型的事件綁定同一個處理
$().bind(json物件); ?//同時綁定多個不同類型的事件
(事件類型:click ?mouseover ?mouseout ?focus ?blur 等等)
事件處理:有名函數(shù)、匿名函數(shù)
<!DOCTYPE html> <html> <head> <title>php.cn</title> <meta charset="utf-8" /> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> //同一個對象綁定多個click事件 $(function(){ $('div').bind('click',function(){ console.log('誰在碰我?'); }); $('div').bind('click',function(){ console.log('誰又在碰我?'); }); $('div').bind('mouseover',function(){ //給div設(shè)置背景色 $(this).css('background-color','lightgreen'); }); $('div').bind('mouseout',function(){ //給div設(shè)置背景色 $(this).css('background-color','lightblue'); }); }); </script> <style type="text/css"> div {width:300px; height:200px; background-color:lightblue;} </style> </head> <body> <div></div> </body> </html>
1.2 取消事件綁定
①?$().unbind(); ?? ?? //取消全部事件
②?$().unbind(事件類型); ?? ?//取消指定類型的事件
③?$().unbind(事件類型,處理); ? //取消指定類型的指定處理事件
注意:第③種取消事件綁定,事件處理必須是有名函數(shù)。
<!DOCTYPE html> <html> <head> <title>php.cn</title> <meta charset="utf-8" /> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> //unbind()取消事件綁定操作 //以下f1和f2要定義到最外邊,使用沒有任何影響 function f1(){ console.log(1111); } function f2(){ console.log(2222); } $(function(){ $('div').bind('click',function(){ console.log('誰在碰我?'); }); $('div').bind('click',function(){ console.log('誰又在碰我?'); }); $('div').bind('click',f1); $('div').bind('click',f2); $('div').bind('mouseover',function(){ //給div設(shè)置背景色 $(this).css('background-color','lightgreen'); //$('div').css('background-color','lightgreen'); }); $('div').bind('mouseout',function(){ //給div設(shè)置背景色 $(this).css('background-color','lightblue'); //$('div').css('background-color','lightgreen'); }); }); function cancel(){ //取消事件綁定 $('div').unbind(); //取消全部事件 } </script> <style type="text/css"> div {width:300px; height:200px; background-color:lightblue;} </style> </head> <body> <div></div> <input type="button" value="取消" onclick="cancel()"> </body> </html>
事件綁定是豐富事件操作的形式而已。