jQuery学习教程,八:事件

绑定事件

jQuery绑定事件方法:

bind(type[,data],fn)//type: 事件类型;data:作为event.data传递给对象的参数;fn:绑定的处理函数

示例,在《锋利的jQuery》一书中讲到了这个例子:

$(function(){  
        $("#panel h5.head").bind("click",function(){  
                if($(this).next("div.content").is(":visiable")){  
                        $(this).next("div.content").hide();  
                }else{ 
                        $(this).next("div.content").show();  
                }  
        });  
});

  

该例子是用来实现点击上面文字隐藏或显示下面文字,经过测试发现只能显示无法隐藏。可能是上面的$(this)函数默认为匿名函数指向的是$(this).next("div.content")了。因此经过改进后的函数修正此bug

$(function(){  
        $("#panel h5.head").bind("click",function(){  
                var $content = $(this).next("div.content"); 
                if($content.is(":visible")){  
                        $content.hide(); 
                }else{ 
                        $content.show(); 
                }  
        })  
});

以上代码可简写:

$("#panel h5.head").click(function(){  
        var $content=$(this).next("div.content"); 
        if($content.is(":visible")){  
                $content.hide(); 
        }else{  
                $content.show(); 
        }  
}

针对使用频繁的onmouseover,onmouseout,jQuery使用了合成事件的方法:

hover(enter,leave)方法//模拟光标悬停事件,光标移动到 元素上触发enter函数,移出元素时触发leave函数。

<script type="text/javascript"> 
        $(function(){  
                $("#source").hover(function(){  
                $("#pointer").text("移入光标");},function(){  
                $("#pointer").text("移出光标");});  
        })
</script>
<div ></div> 
<div ></div>

  

toggle(fc1,fc2,fc3,fc4,…)//该 函数实现模拟鼠标连续单击事件,依次触发fn1,fn2,fn3,fn4……。(一般应用不多)

事件冒泡与事件捕获

事件冒泡:一种很形象的说法;事件会按照DOM的层次结构像水泡一样不断向上直到顶端。

事件捕获:与事件冒泡相反,从最顶端往下触发。

事件解除绑定

删除元素的注册事件,ie中的detachEvent,ff中的removeEventListener中。

$("#btn").click(function(){  
         alert("点击"); 
         $(this).unbind(); 
});

模拟操作

trigger(event)//触发事件

trigger可为元素一次性绑定多个事件。

$("#btn").bind("mouseover mouseout",function(){ 
        $(this).toggleClass("over");  
});