JQuery笔记(五)-事件

JQuery中对事件的支持尤为强大,这里只做简单的介绍,详细的资料还是要去官方站点获取。

 

1.绑定事件

 

  function testA(event){

       alert( event.data.msg);

  }

  $("div").bind("click mousedown",{msg: message},testA}; //将testA绑定到<div>的click事件上,并传入变量message

 

  1.1分别将不同的eventhandler绑定到不同的事件上

       function testA(){}

       function testB(){}

       function testC(){}

 

      $("div").bind({click:testA,mousedown:testB})

 

  1.2绑定的事件中加入namespace

       function testA(){}

       function testB(){}

 

       $("div").bind("click",testA);

       $("div").bind("click.snake",testB); //将testB绑定到snake中的click

 

        完成绑定后,点击鼠标,即可出发testA和testB

 

       $("div").unbind(".snake"); //将snake中的所有click解除绑定。

 

 2.trigger

    $('#foo').bind('custom', function(event, param1, param2) { alert(param1 + "/n" + param2);});

    $('#foo').trigger('custom', ['Custom', 'Event']);

 

    $('#foo').trigger("click.snake") //触发namespace 为snake的click事件

 

 3.event object

    JQuery会向event handler传送event object

    通过event object,可以获得很多环境变量,而且传入的参数也可以在event object找到,如上面的例子。由于篇幅所限,我们不一一列出  event object 的方法和属性,请查阅官方文档

 

  4.live和die

 

     在上面介绍的事件绑定方法都是在定义期就需要明确的,但是在实际应用中,如果动态添加一个dom节点后,也需要根据定义将事件动态绑定到它的上面。这里就需要利用live()方法了

 

     $('.clickme').live('click', function() {// Live handler called.});

     $('body').append('<div class="clickme">Another target</div>');

 

     这里有JQuery对live工作原理的简介:

 

  1. A click event is generated and passed to the <div> for handling.
  2. No handler is directly bound to the <div> , so the event bubbles up the DOM tree.
  3. The event bubbles up until it reaches the root of the tree, which is where .live() binds its special handlers by default.
  4. The special click handler bound by .live() executes.
  5. This handler tests the target of the event object to see whether it should continue. This test is performed by checking if $(event.target).closest('.clickme') is able to locate a matching element.
  6. If a matching element is found, the original handler is called on it.

      die()函数是用来解除live()绑定的事件

 

  5.方便的hover 和 toggle

 

      hover( handlerIn(eventObject), handlerOut(eventObject) )

      handlerIn(eventObject) A function to execute when the mouse pointer enters the element.

      handlerOut(eventObject) A function to execute when the mouse pointer leaves the element.

 

      .toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )

       //Bind two or more handlers to the matched elements, to be executed on alternate clicks.

 

      .toggle( [ duration ], [ callback ] )

      // Display or hide the matched elements.

 

      $("p").toggle("slow");

      $("p").toggle( flip++ % 2 == 0 );

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值