0
点赞
收藏
分享

微信扫一扫

jQuery绑定和触发事件

小暴龙要抱抱 2022-01-28 阅读 150

jQuery操作事件无非就是绑定事件,触发事件,解绑定事件.原生js中的通过DOM编程和在标签上的事件属性绑定事件,

jQuery中,我们可以使用

事件的绑定:bind(),live()(1.8及之前可用),on()(1.9之后推荐使用),one()

事件解绑定:unbind()

事件的触发:行为触发, jQuery方法触发

bind 方法绑定事件,在jQuery中,事件的名称 = 原始名称去掉 on
例如
onclick ——》 click
onmouseover ——》 mouseover

案例

<!DOCTYPE html>
<html>
    <head>
         <meta charset="UTF-8">
         <title></title>
         <style>
             #d1{
                  width: 200px;
                  height: 200px;
                  border: 1px solid red;
             }
         </style>
         <script type="text/javascript"   src="js/jquery.min.js"   ></script>
         <script>
            function fun1(){
            	/*$("#d1").bind('mouseover',function(){
            		$("#d1").css("background-color","yellow")
            	})
            	
            	$("#d1").mouseleave(function(){
            		$("#d1").css("background-color","green")
            	})*/
            	
            	/*
            	 one:绑定一次事件
            
            	 * */
            	$("#d1").one('mouseover',function(){
            		$("#d1").css("background-color","yellow")
            	})
            	
            	$("#d1").one('mouseleave',function(){
            		$("#d1").css("background-color","green")
            	})
            }
            
            function fun2(){
            	//$("#d1").unbind()	//解除绑定的所有事件
            	
            	$("#d1").unbind("mouseover")   // 接触绑定的指定事件
            	
            }
            
            function fun3(){
            	$("#i1").focus()
            }
            function fun4(){
            	console.log("获得了焦点")
            }
         </script>
    </head>
    <body>
         <div id='d1'>
         	
         </div>
         <input type="button"   value="添加事件" onclick="fun1()" />
         <input type="button"   value="解除绑定" onclick="fun2()" />
         <br />
         <input type="text"  id='i1' onfocus="fun4()"/>
         <input type="button"   value="触发事件" onclick="fun3()" />
    </body>
</html>
举报

相关推荐

0 条评论