学习backbone.js的初始阶段(甚至是Js infact)。 html页面有3张图片。我想在点击时替换第一张图片。我这样做是为了学习过程。请告诉我代码或逻辑有什么问题。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World in Backbone.js</title>
</head>
<body>
<!-- HTML CODE -->
<div align="center">
<img src="pic1.jpg" id = "pic1" />
<img src="pic2.jpg" id = "pic2" />
<img src="pic3.jpg" id = "pic3" />
</div>
<!-- Libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script>
<!-- Javascript code -->
<script type="text/javascript">
var AppView = Backbone.View.extend({
el: 'body',
initialize: function(){
this.render();
},
events: function(){
"click #pic1": "replacePic1"
},
render: function(){
console.log('view rendered. try clicking pic1');
//this.$el.html(this.template({who: 'world!'}));
},
replacePic1: function(){
alert("You can replace Pic1");
}
});
var appView = new AppView();
</script>
</body>
</html>
答案 0 :(得分:1)
你可以改进很多但只是为了让事情继续下去并尝试删除你拥有的onClick。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Hello World in Backbone.js</title>
</head>
<body>
<!-- HTML CODE -->
<div align="center">
<img src="pic1.jpg" id = "pic1"/>
<img src="pic2.jpg" id = "pic2" />
<img src="pic3.jpg" id = "pic3" />
</div>
<!-- Libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script>
<!-- Javascript code -->
<script type="text/javascript">
var AppView = Backbone.View.extend({
el: 'body',
initialize: function(){
this.render();
},
events: {
"click #pic1": "replacePic1"
},
render: function(){
console.log('view rendered. try clicking pic1');
//this.$el.html(this.template({who: 'world!'}));
},
replacePic1: function(){
$("#pic1").attr('src',"new/url.jpg");
}
});
var appView = new AppView();
</script>
</body>
</html>
显然,这不是你想要做的事情,但可能值得尝试。我找到的一个很棒的骨干教程系列是Wine Cellar Tutorial。按照整个系列,您将学到很多东西。请使用Lessons Learned文章进行跟进,然后享受:)