【问题标题】:Sammy cannot find element? JSSammy 找不到元素? JS
【发布时间】:2020-03-29 14:53:10
【问题描述】:

我正在尝试将 Sammy 用于我的 SPA,但我无法处理此错误:

[Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get /  Error: 404 Not Found get / 
    at Sammy.Application.error (sammy-latest.min.js:5)
    at Sammy.Application.notFound (sammy-latest.min.js:5)
    at Sammy.Application.runRoute (sammy-latest.min.js:5)
    at Sammy.Application._checkLocation (sammy-latest.min.js:5)
    at Sammy.Application.run (sammy-latest.min.js:5)
    at app.js:23
    at app.js:24 

似乎应用程序在 HTML 文件中找不到元素,但它就在那里。这是我的 JS 代码以及我在 index.html 中导入的内容:

(()=>{
    const app = Sammy('#main', function(){
        console.log('Hello');
    })
    app.run('/#');
})()

HTML:

    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
    <script src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="./node_modules/handlebars/dist/handlebars.min.js"></script>
    <script src="./node_modules/sammy/lib/min/sammy-latest.min.js"></script>
    <script src="./node_modules/sammy/lib/plugins/sammy.handlebars.js"></script>

(我需要使用 id='main' 的 div)

我应该做一些其他的配置吗?

【问题讨论】:

  • 我不是 Sammy.js 方面的专家,但在网页上他们说的是 app.run('#/'); 而不是 app.run('/#');

标签: javascript jquery single-page-application sammy.js


【解决方案1】:

正如@Dominique 在评论中所说,您应该使用app.run('#/') 而不是app.run('/#') 运行应用程序。

另外,您没有正确使用 SammyJS。 如果你想使用“基本”routes,你可以使用 GET 方法:

const app = Sammy('#main', function(){
  // Here you should create routes, and not write code

  // Example : Home page : your.site/page.html
  this.get('#/', function() {
    console.log("Welcome Home");
  });   

  // Exemple : your.site/page.html#/sayhello
  this.get('#/sayhello', function() {
    console.log("Hello");
  });   
})

您可以使用URL来使用参数,例如,如果您想在控制台中显示您在URL中写入的内容:

var app = Sammy('#main', function() {

  // msg is a variable, where its value comes from the url
  this.get('#/display/:msg',function(c) {
    console.log(c.params.msg);
  });

}

那么如果你去your.site/page.html#/display/I_love_donuts,I_love_donuts会在控制台打印出来。

当我开始学习 SammyJS 时,我发现这个速成课程非常有用:https://www.youtube.com/watch?v=QBKm444gO0U。如果您对 SammyJS 还不满意,我建议您观看它。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2017-01-06
    • 2019-11-16
    • 2014-01-27
    • 2018-03-08
    • 2017-08-30
    • 2021-04-24
    • 2017-12-21
    • 2019-01-02
    相关资源
    最近更新 更多