jQuery Mobile委托vs实时vs绑定 [英] jQuery Mobile delegate vs live vs bind

查看:65
本文介绍了jQuery Mobile委托vs实时vs绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't seem to wrap my head around the differences between the following in jQuery Mobile:

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

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

$( document ).delegate("#page", "pageshow", function() {
});

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

How do I execute scripts in the head of my documents that are DIFFERENT in certain pages? Which methods do I use to call those scripts?

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

Update: jQuery version: 1.7.1 jQuery Mobile version: 1.1.0

推荐答案

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

You would bind to a "page event" that jQuery Mobile exposes, like pageinit:

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

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

Since you're using jQuery Core 1.7.1 you can use .on() which has a slightly different syntax:

$(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()时,必须确定在事件处理程序中而不是在函数调用中向其触发了哪个伪页面

All three of your methods do similar things. .live() is the same thing as using .delegate() with document as the root selection but it's been depreciated so it's a good idea to stop using it (source: http://api.jquery.com/on). Using .bind() directly on the document element is the same as using .delegate() but when you use .bind() you have to determine which pseudo-page had the event fired on it in the event handler rather than in the function call.

例如:

$(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元素).

In general, event delegation is used when we don't know when an element will exist in the DOM. It relies on events bubbling up the DOM until they get to the root selection (in your case it's always the document element).

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

有关这些功能之间差异的更多常规信息,请参阅本文(我已阅读该文章以检查其准确性,并且它是正确的):

For more general information about the difference between these functions, see this article (I've read it to check it for accuracy and it's right-on): http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html

这篇关于jQuery Mobile委托vs实时vs绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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