jquery - 有没有更好的方法在 jQuery Mobile 中附加到 pageshow?

标签 jquery ajax delegates jquery-mobile

我有一个每当显示页面时都需要调用的函数,无论是通过标准页面加载还是通过 jQuery Mobile 的 AJAX 导航机制。目前,我的代码工作没有问题,但我觉得有一种更优雅的方法。

在我的页面的页脚中,我有一些代码附加到该页面的 pageshow 事件。在 pageshow 上,它将聚焦于文本框,执行警报(用于测试),然后将自身与 pageshow 事件解除绑定(bind)。如果我不取消绑定(bind),那么如果我离开该页面然后返回该页面,该事件将触发两次。对于焦点事件来说并不是什么大问题,但是如果您尝试使用警报,您会看到它们开始堆积:P

var focusOnQuantity = function () {
    $("#quantity").focus();
    alert('test');
    $('body').undelegate('#reportProduction', 'pageshow', focusOnQuantity);
};

// Bind to this page's pageshow event when loaded via jQuery Mobile AJAX
$('body').delegate('#reportProduction', 'pageshow', focusOnQuantity);

我还有一个全局 JS,其中有一个 jQuery 保护函数,在直接加载此页面的情况下,我会进行相同的焦点调用。

(function ($) {
    $(function () {
        // For direct page load
        $("#quantity").focus();
    });
})(jQuery);

如何将代码封装到 1 个 block 中,以便它可以在用于标准导航的 pageload 和用于 AJAX 导航的 pageshow 上工作?预先感谢您的帮助。

最佳答案

如果您只是绑定(bind)到 pageshow 事件,它将在初始加载以及每个后续 pageshow 时触发:

$(document).delegate('#reportProduction', 'pageshow', focusOnQuantity);

如果此代码在全局范围内运行,则它只应在 #reportProduction 页面上的每个 pageshow 事件中运行一次。

这是上述解决方案的jsfiddle:http://jsfiddle.net/jasper/DHeva/ (请注意,我已将“onLoad”首选项更改为“no wrap (body)”,这意味着代码将附加到 body 元素的末尾,而不使用 $(function ( ) {...});).

关于jquery - 有没有更好的方法在 jQuery Mobile 中附加到 pageshow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228398/

相关文章:

javascript - jQuery :not and :first ordering

javascript - jQuery 在点击时遍历数组

jquery - jQuery AJAX 中带有 ajaxStop 的递归调用函数

ios - 检测 UITabBarController 的标签栏项目更改

c# - ILGenerator : Load created method

javascript - 在jquery中结合toggle和fadeTo

php - 表单不将数据保存到 MySQL 数据库

jquery - 使用 jQuery.find() 和 XML 文档获取 HTMLUnknownElement

ios - Swift 类的 Objective-c 协议(protocol)。无法识别的方法

jquery - 使用 jQuery 获取原始 XML 节点