zoukankan      html  css  js  c++  java
  • jQuery中的事件绑定的几种方式

    jQuery目前有on(),bind(),delegate(),live()四种绑定方式,但是随着版本的不断更新,有的方式也相应的被淘汰掉

    【band()方式绑定】

        3.0版本之前的绑定方式比较常用的是bind()绑定事件,解除事件的方式是unbind(),但是在3.0之后band()的绑定方式也别相应的解除掉了。bind()的事件绑定是只对当前页面选中的元素有效。如果你想对动态创建的元素bind()事件,是没有办法达到效果的,如下代码。

     1 <body>
     2 <button id="add" type="button">add DIV</button>
     3 <button id="del" type="button">del DIV</button>
     4 <button id="onBtn" type="button">绑定事件</button>
     5 <button id="offBtn" type="button">解绑事件</button>
     6 <div id="container">
     7     <div class='created'>我是原生div<div/>
     8 </div>
     9 </body>
    10 <script>
    11     $(function () {
    12         $("#add").click(function(){
    13             $("#container").prepend("<div class='created'>我是动态生成的div<div/>")
    14         });
    15         $("#del").click(function(){
    16             $("div").remove(".created:first")
    17         });
    18         $("#onBtn").click(function(){
    19             $("#container").on("click",".created",function(){
    20                 alert(1);
    21             });
    22         });
    23         $("#offBtn").click(function(){
    24             $("#container").off("click");
    25         })
    26     })
    27 </script>

    delegate(),live()两种绑定方式并不太常用,因此推荐下面这种方式,on()绑定。

    【on()事件绑定】

    ① 使用on进行单事件绑定

    $("button").on("click",function(){
    $(this) 取到当前调用事件函数的对象
    console.log($(this).html());
    });


     ② 使用on同时为多个事件,绑定同一函数
    $("button").on("mouseover click",function(){
    console.log($(this).html())
    });

     ③ 调用函数时,传入自定义参数
    $("button").on("click",{name:"jianghao"},function(event){
    使用event.data.属性名 找到传入的参数
    console.log(event.data.name);
    })

    ④ 使用on进行多事件多函数绑定
    $("button").on({
    click:function(){
    console.log("click")
    },
    mouseover:function(){
    console.log("mouseOver")
    }
    });

    ⑤ 使用on进行事件委派
     >>> 将原本需要绑定到某元素上的事件,改为绑定在父元素乃至根节点上,然后委派给当前元素生效;
    eg:$("p").click(function(){});
     $(document).on("click","p",function(){});
    作用:
    默认的绑定方式,只能绑定到页面初始时已有的p元素,当页面新增p元素时,无法绑定到新元素上;
    使用事件委派方式,当页面新增元素时,可以为所有新元素绑定事件

    off() 取消事件绑定
    1. $("p").off(): 取消所有事件
    2. $("p").off("click"): 取消点击事件
    3. $("p").off("click mouseover"):取消多个事件
    4. $(document).off("click","p"):取消事件委派

  • 相关阅读:
    测试WCF遇到的一些问题
    Webservices部署在IIS6.0上的一个小问题
    同程面试经历
    IIS6.0+win2003部署MVC网站的一些问题
    C++ 结构体初始化
    Sicily 1146:采药(dp)
    Sicily 10359:Valuable Jewellery(贪心+优先队列)
    Sicily 2503:最长字符串(贪心)
    MATLAB产生离散信号
    Sicily 1681: Matchsticks(贪心)
  • 原文地址:https://www.cnblogs.com/GlenLi/p/6886675.html
Copyright © 2011-2022 走看看