我无法让sammy.js路由按预期工作.
我有以下JavaScript.
(function ($) {
var app = $.sammy('#main', function () {
this.get('#/', function (context) {
context.log("start page");
});
this.get("#/another/:id/", function (context) {
context.log("another page with id = " + context.params["id"]);
});
});
$(function (context) {
app.run('#/');
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
我的理解是,每当URL发生变化时,只要新路由对应于其中一条声明的路由,我就应该在控制台日志中看到相关的消息.
但我没有.
当页面首次加载时,我可以看到"开始页面"消息.到现在为止还挺好.
如果我那么
......没有任何反应,即我没有看到第二条路线的消息.
但是,使用地址栏中的第二条路线,如果我现在按F5或单击浏览器的刷新按钮,则页面将重新加载并显示预期的控制台消息.
我是否误解了,或者当超链接或键盘更改了URL哈希时Sammy会注意到,然后相应地采取行动?我需要在脚本中添加其他内容吗?
每个sammy应用程序都需要附加到DOM元素.
所以你可能错过了#main页面中的元素.
所以你需要#main在你的DOM中添加一个元素:
<div id="main">
</div>
Run Code Online (Sandbox Code Playgroud)
或者你需要在没有选择器的情况下初始化sammy
var app = $.sammy(function () {
this.get('#/', function (context) {
context.log("start page");
});
this.get("#/another/:id/", function (context) {
context.log("another page with id = " + context.params["id"]);
});
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它将自身附加到body元素上.
现场演示.