zoukankan      html  css  js  c++  java
  • Jquery动态绑定事件处理函数 bind / on / delegate

    1、bind方法绑定的事件处理函数不会应用到后来添加到DOM中的新元素。比如你在用bind给页面元素绑定事件之后,又新添加了一些与之前绑定过事件的元素一样的DOM元素,但是这些事件并不能在新的DOM元素上有体现。

    如:

     $(document).ready(function(){
          $("img").bind({
              mouseenter:function(){
                       $(this).css("border","thick solid red");
               },
               mouseout:function(){
                      $(this).css("border","thick solid green");
               }
             });
           $("#row").append("<img src='./idiot.png'/>");
          });

    此时新插入的img并没有绑定事件。

    2、on方法绑定事件,并非直接把事件处理函数绑定到目标元素上。实际上它是在document对象上绑定了一个事件处理函数,该函数在触发时检查触发事件的元素是否匹配选择器。一旦事件与元素匹配成功,就调用绑定的事件处理函数。实际上,on方法是努力的把事件处理函数绑定要新的元素上。

    $(document).ready(function(){
          $(document).on({
              mouseenter:function(){
                       $(this).css("border","thick solid red");
               },
               mouseout:function(){
                      $(this).css("border","thick solid green");
               }
             },"img"); 
    $(
    "#row").append("<img src='./idiot.png'/>");
    }
    );

    但是,on方法绑定事件处理函数可能会有一个问题,在处理函数执行之前,我们需要等事件传播到document元素,与on方法相比delegate更直接、高效一些。

    3、delegate方法绑定事件,允许我们在页面上指定任意一个元素作为监听事件的元素,只绑定一个事件处理函数,绑定速度相对于bind和on算更快的。

    $(document).ready(function(){
          $("#row").delegate("img",{ 
          
          mouseenter:function(){
            $(this).css("border","thick solid red"); 
          },
          mouseout:function(){
            $(this).css("border","thick solid green");
          }
        },);
        $("#row").append("<img src='./idiot.png'/>");
    });
  • 相关阅读:
    【Network】OVS、VXLAN/GRE、OVN等 实现 Docker/Kubernetes 网络的多租户隔离
    【openStack】Libcloud 如何支持 keystone V3?
    【Network】修改docker启动默认网桥docker0为自定义网桥
    【Network】TCPDUMP 详解
    【Network】OVS基础知识
    【Docker】Docker主机为什么ip nets 查不到网络空间
    sql-in/not in和exists/not exists的区别
    sql-exists和not exists
    oracle-分页查询方案
    mysql-函数FOUND_ROWS()
  • 原文地址:https://www.cnblogs.com/1rookie/p/7866882.html
Copyright © 2011-2022 走看看