jQuery Mobile委托vs live vs bind

cus*_*ice 11 jquery jquery-mobile

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

$( document ).live('pageshow', function(event) {
});

$( document ).bind('pageshow', function(event) {
});

$( document ).delegate("#page", "pageshow", function() {
});
Run Code Online (Sandbox Code Playgroud)

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

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

Jas*_*per 15

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

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

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

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

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

例如:

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

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

文档.delegate():http://api.jquery.com/delegate

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