gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:22:53 24 4
gpt4 key购买 nike

我有一个每当显示页面时都需要调用的函数,无论是通过标准页面加载还是通过 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com