jquery一些 事件的用法

在jquery中有许多的事件,在使用时可分为两类吧,一种是基本的事件,如click、blur、change、foucus等,这些是通过简单封装js用法,使用如:
  1. $("a[name=link]").click(function(event){
  2. //事件event;可用多个对象进行绑定用逗号分割 $("div,#link").click();
  3. event.stopPropagation();//不再派发事件
  4. });
$("a[name=link]").click(function(event){
   //事件event;可用多个对象进行绑定用逗号分割 $("div,#link").click();
   event.stopPropagation();//不再派发事件
});
  1. $("a[name=link]").keydown(function(event){//事件event
  2. if(event.keyCode=='13'){//记录点击的键盘编码 13为回车
  3. event.preventDefault();//不要执行与事件关联的默认动作
  4. }
  5. });
$("a[name=link]").keydown(function(event){//事件event
   if(event.keyCode=='13'){//记录点击的键盘编码 13为回车
      event.preventDefault();//不要执行与事件关联的默认动作
   }
});
//etc.

以上俩个例子,就是触发浏览器中的行为,还有很多,可参考jquety的文档,主要介绍是jquery所提供的其他方法如:bind,live,toggle,trigger,hover

1、bind()与unbind()

bind()是将元素进行行为上的绑定 例:

  1. $("a[name=link]").bind("click",function(event){//绑定click事件
  2. alert(event.pageX);//点击处x轴位置
  3. alert(event.pageY);//点击处Y轴位置
  4. });
  5. $("a[name=link]").bind("mouseenter mouseleave",function(){//绑定多个事件 鼠标移入移出
  6. //do something
  7. });
$("a[name=link]").bind("click",function(event){//绑定click事件
  alert(event.pageX);//点击处x轴位置  
  alert(event.pageY);//点击处Y轴位置
});

$("a[name=link]").bind("mouseenter mouseleave",function(){//绑定多个事件 鼠标移入移出
  //do something
});
uubind() 顾名思义 是解除绑定

  1. $("a[name=link]").unbind();//不加参数就解除此对象所有事件
$("a[name=link]").unbind();//不加参数就解除此对象所有事件
需要注意一下,当我们用js去给文档添加元素的时候,bind已经绑定的动作是失效的,除非添加元素后再重新绑定,或者使用live()去进行绑定 例如

  1. <div id="demo">
  2. <div>
  3. $("#demo").append("<a href='javascript:void(0)' id='link'>text</a>");
  4. $("#link").bind("click",function(){//这种事不效果的
  5. alert(1);
  6. });
<div id="demo">
  
<div>
$("#demo").append("<a href='javascript:void(0)' id='link'>text</a>");
$("#link").bind("click",function(){//这种事不效果的
   alert(1);
});
2、live()是指附加处理器的元素,跟bind()用法基本一致,区别是live()可以使元素在任何时候添加,仍然响应事件
例子同bind() 就不举例说明了,注意区别就行了

3、toggle() 按照顺序依次调用指定的函数,然后重复调用,一般会做事件轮转切换,做动画效果

  1. $("a[name=link]").toggle(//点击一下会弹出1 再点击为2 。。3.。1.。2.。3.。。。
  2. function(){alert(1);},
  3. function(){alert(2);},
  4. function(){alert(3);}
  5. );
$("a[name=link]").toggle(//点击一下会弹出1 再点击为2 。。3.。1.。2.。3.。。。
                 function(){alert(1);},
                 function(){alert(2);},
                 function(){alert(3);}
);
如果没有参数为隐藏显示转换 可加参数 毫秒数或者slow fast字符串,详细请看jquery文档吧~

文档的例子很详细这就不在阐述了

4、trigger()是触发被选元素的事件

如当我们绑定了一个click事件,我们就可以通过trigger()去触发

  1. $("#link").bind("click",function(event){
  2. alert(1);
  3. });
  4. $("#link").trigger("click");
$("#link").bind("click",function(event){
    alert(1);
});
$("#link").trigger("click");
5、hover()是同时绑定mouseenter()mouseleave()的事件,对做鼠标移入移出的动画效果还是很方便的

  1. $("a[name=link]").hover(
  2. function () {
  3. $(this).append($("<span> ***</span>"));
  4. },
  5. function () {
  6. $(this).find("span:last").remove();
  7. }
  8. );
原文地址:https://www.cnblogs.com/yangkai-cn/p/4016749.html