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"):取消事件委派

  • 相关阅读:
    Eclipse 远程调试
    大数据处理方法bloom filter
    sicily 1259 Sum of Consecutive Primes
    sicily 1240. Faulty Odometer
    sicily 1152 简单马周游 深度优先搜索及回溯算法
    sicily 1050 深度优先搜索解题
    sicily 1024 邻接矩阵与深度优先搜索解题
    sicily 1156 二叉树的遍历 前序遍历,递归,集合操作
    sicily 1443 队列基本操作
    sicily 1006 team rankings 枚举解题
  • 原文地址:https://www.cnblogs.com/GlenLi/p/6886675.html
Copyright © 2011-2022 走看看