JavaScript中的代码相同,结果不同
这是我的第一个问题。在Azat Mardan的帮助下,我正在学习Javascript,特别是Backbone.js 第4章介绍了Backbone.js框架,并通过教程和示例进行了说明。到目前为止,我还没有遇到直接遵循这本书的代码的问题。然而,我一直试图复制示例代码,但它不起作用。但是,当我直接从github复制源代码时,它却莫名其妙地工作了 这是我的密码。作者的代码可在上找到 之间)和{JavaScript中的代码相同,结果不同,javascript,html,backbone.js,Javascript,Html,Backbone.js,这是我的第一个问题。在Azat Mardan的帮助下,我正在学习Javascript,特别是Backbone.js 第4章介绍了Backbone.js框架,并通过教程和示例进行了说明。到目前为止,我还没有遇到直接遵循这本书的代码的问题。然而,我一直试图复制示例代码,但它不起作用。但是,当我直接从github复制源代码时,它却莫名其妙地工作了 这是我的密码。作者的代码可在上找到 之间)和{ 谢谢你的帮助!不要复制他模板中的反斜杠(\),要么将所有内容保持在一行,要么将字符串与+连接起来。我继续复制
谢谢你的帮助!不要复制他模板中的反斜杠(
\
),要么将所有内容保持在一行,要么将字符串与+
连接起来。我继续复制了你的代码,你可以看到它工作了:
以下是Google的JavaScript风格指南中的更多内容。控制台会说什么,有错误吗?@elclanrs“未捕获的语法错误:意外标识符:第70行”这一条-->showSpinner:function(){这意味着缺少逗号,你确定你正在显示的代码没有缺少逗号吗?我在那里找不到这样的错误。无论如何,这是我看到的messier JS代码片段之一。确实有一种可能性是,你的原始代码在``行延续中有空格,但这可能会导致另一个错误。我不能投票我已经把你的答案填好了,不过谢谢,我会查那个指南的!
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script>
var appleData = [
{
name: "fuji",
url: "img/fuji.jpg"
},
{
name: "gala",
url: "img/gala.jpg"
}
];
var app;
var router = Backbone.Router.extend({
routes: {
'': 'home',
'apples/:appleName':'loadApple'
},
initialize: function(){
var apples = new Apples();
apples.reset(appleData);
this.homeView = new homeView({collection: apples});
this.appleView = new appleView({collection: apples});
},
home: function(){
this.homeView.render();
},
loadApple: function(appleName){
this.appleView.loadApple(appleName);
}
});
var homeView = Backbone.View.extend({
el: 'body',
template: _.template('Apple data: <%= data %>'),
render: function(){
this.$el.html(this.template({data: JSON.stringify(this.collection.models)}));
}
});
var Apples = Backbone.Collection.extend({
});
var appleView = Backbone.View.extend({
initialize: function() {
this.model = new (Backbone.Model.extend({}));
this.model.on('change', this.render, this);
this.on('spinner', this.showSpinner , this);
},
template: _.template('<figure>\
<img src="<%= attributes.url %>"/>\
<figcaption><%= attributes.name %></figcaption>\
</figure>'),
templateSpinner: '<img src="img/spinner.gif" width="30"/>',
loadApple: function(appleName){
this.trigger('spinner');
var view = this;
setTimeout(function(){
view.model.set(view.collection.where({name:appleName})[0].attributes);
},1000);
},
render: function(appleName) {
var appleHtml = this.template(this.model);
$('body').html(appleHtml);
},
showSpinner: function() {
$('body').html(this.templateSpinner);
}
});
$(document).ready(function(){
app = new router;
Backbone.history.start();
});
</script>
</head>
<body>
<div></div>
</body>
</html>
showSpinner: function(){