.live()与.bind() [英] .live() vs .bind()

查看:64
本文介绍了.live()与.bind()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道两者之间的主要区别

I want to know the main difference between

.live().bind()

jQuery中的方法.

methods in jQuery.

推荐答案

主要区别在于,live对于在页面加载后创建的元素(即,通过您的javascript代码)也将起作用,而bind仅将事件处理程序绑定到当前存在的项目.

The main difference is that live will work also for the elements that will be created after the page has been loaded (i.e. by your javascript code), while bind will only bind event handlers for currently existing items.

// BIND example
$('div').bind('mouseover', doSomething);
// this new div WILL NOT HAVE mouseover event handler registered
$('<div/>').appendTo('div:last');

// LIVE example
$('div').live('mouseover', doSomething);
// this new appended div WILL HAVE mouseover event handler registered
$('<div/>').appendTo('div:last');

更新:

jQuery 1.7不推荐使用live()方法,而1.9已将其删除.如果要使用1.9+实现相同的功能,则需要使用新的方法on(),该方法的语法与在文档对象上调用的语法略有不同,并且选择器作为参数传递.因此,从上面转换为这种新的绑定事件方式的代码将如下所示:

jQuery 1.7 deprecated live() method and 1.9 has removed it. If you want to achieve the same functionality with 1.9+ you need to use a new method on() which has slightly different syntax as it's invoked on document object and the selector is passed as a parameter. Therefor the code from above converted to this new way of binding events will look like this:

// ON example
$(document).on('mouseover', 'div', doSomething);
// this new appended div WILL HAVE mouseover event handler registered
$('<div/>').appendTo('div:last');

这篇关于.live()与.bind()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆