jQuery Mobile委托vs live vs bind

我似乎无法理解jQuery Mobile中以下内容之间的差异:

$( document ).live('pageshow', function(event) { }); $( document ).bind('pageshow', function(event) { }); $( document ).delegate("#page", "pageshow", function() { }); 

如何在某些页面中不同文档的头部执行脚本? 我用哪种方法来调用这些脚本?

更新:jQuery版本:1.7.1 jQuery Mobile版本:1.1.0

您将绑定到jQuery Mobile公开的“页面事件”,例如pageinit

 $(document).delegate('#my-page', 'pageinit', function () { //this is like document.ready for this pseudo-page }); 

由于你使用的是jQuery Core 1.7.1,你可以使用.on() ,它的语法略有不同:

 $(document).on('pageinit', '#my-page', function () { //this is like document.ready for this pseudo-page }); 

你的所有三种方法都做类似的事情。 .live()与使用.delegate()document作为根选择相同,但它已被折旧,因此最好停止使用它(来源: http : //api.jquery.com/on )。 直接在document元素上使用.bind()与使用.delegate()相同,但是当你使用.bind()你必须确定哪个伪页面在事件处理程序中而不是在函数中触发了它。呼叫。

例如:

 $(document).bind('pageshow', function () { var id = $.mobile.activePage[0].id; //you can use $.mobile.activePage to do work on the current page }); 

通常,当我们不知道DOM中何时存在元素时,将使用事件委托。 它依赖于冒泡DOM的事件,直到它们到达根选择(在您的情况下,它始终是document元素)。

.delegate()文档: http : .delegate()

有关这些function之间差异的更多一般信息,请参阅此文章(我已阅读它以检查其准确性并且正确): http : //www.elijahmanor.com/2012/02/differences-between- jquery的绑定-VS-live.html

这是一个很好的描述: http : //jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html

但简短的回答是,如果你使用的是jquery 1.7,你应该开始在()而不是以下任何一个上使用新的API: http : //api.jquery.com/on/

前几天我有同样的问题,发现这篇文章对每一个都提供了明确的细分。

http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html