JQuery学习笔记1——事件绑定

在文档装载完成后,如果想给元素绑定事件来完成某些操作,可以使用bind()方法。

bind()方法的调用格式:bind(type[,data],fn);

第1个参数是事件类型(blur,focus,load,resize,scroll,unload,click,dbclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error等,还可以是自定义的名称)

第2个参数是为可选参数,作为event.data属性值传给事件对象的额外数据对象

第3个参数是用来绑定的处理函数。

 基本HTML代码:

Code

 一.实现基本效果

单击“标题”链接显示出“内容”;再次单击“标题”链接隐藏“内容”

 1 <script type="text/javascript">
 2     $(document).ready(function(){
 3         $("#panel .content").hide();
 4         $("#panel h5.head").bind("click",function(){
 5            if($("div.content").is(":hidden")){
 6                 $(this).next("div.content").show();
 7            }else{
 8                 $(this).next("div.content").hide();       
 9            }            
10         })
11     })    
12 </script>

 二.改变绑定事件的类型

当光标滑过“标题”时显示“内容”;当光标滑出时隐藏“内容”

1 <script type="text/javascript">
2     $(document).ready(function(){
3         $("#panel .content").hide();
4         $("#panel h5.head")
5             .bind("mouseover",function(){$(this).next("div.content").show();})
6             .bind("mouseout",function(){$(this).next("div.content").hide();})
7     })    
8 </script>

 三.简写绑定事件

1 <script type="text/javascript">
2     $(document).ready(function(){
3         $("#panel .content").hide();
4         $("#panel h5.head")
5             .mouseover(function(){$(this).next("div.content").show();})
6             .mouseout(function(){$(this).next("div.content").hide();})
7     })    
8 </script>

  四.hover()方法合成事件

 hover()方法用于模拟光标悬停事件。

 语法结构是:hover(enter,leave);

1 <script type="text/javascript">
2     $(document).ready(function(){
3         $("#panel .content").hide();
4         $("#panel h5.head").hover(
5             function(){$(this).next("div.content").show();},
6             function(){$(this).next("div.content").hide();}
7         );            
8     })    
9 </script>

 五.toggle()方法合成事作

toggle()方法用于模拟鼠标连续单击事件。

语法结构:toggle(fn1,fn2,fn……)

1 <script type="text/javascript">
2     $(document).ready(function(){
3         $("#panel .content").hide();
4         $("#panel h5.head").toggle(
5             function(){$(this).next("div.content").show();},
6             function(){$(this).next("div.content").hide();}
7         );            
8     })    
9 </script>

六.再次加强效果

当用户单击“标题” 按钮时,高亮显示“标题”

首先在样式中添加:#panel .highlight{ background:#000; color:#fff;}

然后编写代码:

 1 <script type="text/javascript">
 2     $(document).ready(function(){
 3         $("#panel .content").hide();
 4         $("#panel h5.head").toggle(
 5             function(){
 6             $(this).addClass("highlight"); //添加高亮样式
 7             $(this).next("div.content").show();},
 8             function(){
 9             $(this).removeClass("highlight"); //移除高亮样式
10             $(this).next("div.content").hide();}
11         );            
12     })    
13 </script>
posted @ 2009-07-10 13:49  郭培  阅读(313)  评论(0编辑  收藏  举报