我使用 SmoothState.js 进行页面转换,它工作正常并使用 ajax 加载新页面。然而,我在每个页面上都有需要重新初始化的 JS 脚本,并且我无法让它们始终出现在页面转换中。
根据常见问题解答:
smoothState.js 提供了 onAfter 回调函数,可以让你
重新运行您的插件。如果您不熟悉的话,这可能会很棘手
AJAX 是如何工作的。
当你在 $(document).ready() 上运行插件时,它将注册
仅适用于当前页面上的元素。由于我们正在注入
每次加载新元素,我们需要再次运行插件,确定其范围
只是新东西。
一个好方法是将插件初始化包装在
我们在 $.fn.ready() 和 onAfter 上调用的函数。你会想要
每次初始化插件时指定上下文,以便您
不要双重绑定它们。这称为“模块执行
控制器”。
我的计划是从 JS 文件中获取函数并将它们全部放入 SmoothState.js 文件内的 onAfter 调用中。这样,每次用户更改页面时,这些功能始终可用。
这是我现在的代码结构。我已经做了很多挖掘,但我被困住了。你能帮我弄清楚我做错了什么吗?谢谢你的时间!
$(document).ready(function() {
mail();
});
$('#main').smoothState({
onAfter: function() {
mail();
}
});
function mail() {
// script from mail.js goes here
}
$(function() {
$('#main').smoothState();
});
$(function() {
"use strict";
var options = {
prefetch: true,
pageCacheSize: 3,
onStart: {
duration: 250, // Duration of our animation
render: function($container) {
// Add your CSS animation reversing class
$container.addClass("is-exiting");
// Restart your animation
smoothState.restartCSSAnimations();
}
},
onReady: {
duration: 0,
render: function($container, $newContent) {
// Remove your CSS animation reversing class
$container.removeClass("is-exiting");
// Inject the new content
$container.html($newContent);
}
},
},
smoothState = $("#main").smoothState(options).data("smoothState");
});
通过将 onAfter 脚本移动到主 smoothstate 函数中(删除其他 smoothstate 函数),我设法在代码末尾运行一个单独的函数。在浏览器刷新的情况下,也可以在文档就绪时运行您的函数。如果它与您的代码工作相同,则如下所示:
$(document).ready(function() {
mail();
});
function mail() {
// script from mail.js goes here
}
$(function() {
"use strict";
var options = {
prefetch: true,
pageCacheSize: 3,
onStart: {
duration: 250, // Duration of our animation
render: function($container) {
// Add your CSS animation reversing class
$container.addClass("is-exiting");
// Restart your animation
smoothState.restartCSSAnimations();
}
},
onReady: {
duration: 0,
render: function($container, $newContent) {
// Remove your CSS animation reversing class
$container.removeClass("is-exiting");
// Inject the new content
$container.html($newContent);
}
},
onAfter: function() {
mail();
}
},
smoothState = $("#main").smoothState(options).data("smoothState");
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)