Sammy路由不起作用 [英] Sammy routing not working

查看:82
本文介绍了Sammy路由不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使sammy.js路由正常工作。

I'm unable to get sammy.js routing working as expected.

我有以下JavaScript。

I have the following 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);

我的理解是,只要URL发生更改,只要新路由对应于以下其中一项声明的路由,那么我应该在控制台日志中看到相关消息。

My understanding is that whenever the URL has changes, and so long as the new route corresponds to one of the declared routes, then I should see the relevant message in the console log.

但是我没有。

页面首次加载时,我会看到开始页面消息。

When the page first loads I can see the "start page" message. So far so good.

如果我那么


  • 单击链接指向[my url] /#/ another / 1 /

  • 手动在地址栏中键入[my url] /#/ another / 1 /,然后按< Enter>

...什么也没发生, ie 我看不到第二条路线的消息。

... nothing happens, i.e. I don't see the message for the second route.

但是,使用地址栏中的第二条路线,如果我现在按F5键或单击浏览器的 refresh 按钮,则页面将重新加载并显示预期的控制台消息。

However, with the second route in the address bar, if I now hit F5 or click the browser's refresh button then the page reloads and shows the expected console message.

我是否误解了,或者当超链接或键盘更改了URL哈希值然后采取相应措施时,Sammy是否应该注意?

Have I misunderstood, or shouldn't Sammy notice when a hyperlink or keyboard has changed the URL hash, and then act accordingly? Is there something else that I need to add to my script?

推荐答案

每个智能应用程序都需要附加到DOM元素。

Each sammy application needs to be attached to a DOM element.

因此,您可能会缺少页面中的 #main 元素。

So you are probably missing the #main element form your page.

因此您需要在DOM中的某个位置添加 #main 元素:

So you need to add a #main element in your DOM somewhere:

<div id="main">
</div>

或者您需要在没有选择器的情况下初始化sammy

or you need to initialize sammy without a selector

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"]);
    });
});

在这种情况下,它将自身附加到 body 元素。

it this case it attaches itself to the body element.

实时演示

这篇关于Sammy路由不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆