问题描述
我似乎无法理解 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.1jQuery 移动版:1.1.0
Update:jQuery version: 1.7.1jQuery 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
有关这些功能之间差异的更多一般信息,请参阅这篇文章(我已阅读它以检查其准确性并且正确):http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html
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 委托与实时与绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!