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'/>");
});