jQuery中.bind() .live() .delegate() .on()的区别

link

jQuery中.bind() .live() .delegate() .on()的区别

content

  • bind(type,[data],fn) 为每个匹配元素的特定事件绑定事件处理函数
    $("a").bind("click",function(){alert("ok");});

  • live(type,[data],fn) 给所有匹配的元素附加一个事件处理函数,即使这个元素是以后再添加进来的
    $("a").live("click",function(){alert("ok");});

  • delegate(selector,[type],[data],fn) 指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数
    $("#container").delegate("a","click",function(){alert("ok");})

  • on(events,[selector],[data],fn) 在选择元素上绑定一个或多个事件的事件处理函数

差别:

  • .bind()是直接绑定在元素上

  • .live()则是通过冒泡的方式来绑定到元素上的。更适合列表类型的,绑定到document DOM节点上。和.bind()的优势是支持动态数据。

  • .delegate()则是更精确的小范围使用事件代理,性能优于.live()

  • .on()则是最新的1.9版本整合了之前的三种方式的新事件绑定机制

猜你喜欢

转载自blog.csdn.net/wuyujin1997/article/details/89630394