我开始使用 Backbone.js 并尝试使用 javascript 做一些简单的事情,即显示/隐藏 div。我可以显示 div 但我无法隐藏它,我尝试了很多东西,知道吗?还是可以更复杂?
var Step1View = Backbone.View.extend({
el: $('body'),
events: {
'click #more': 'more',
'click #hide': 'hide',
},
initialize: function (){
_.bindAll(this, 'render', 'more', 'next', 'less');
this.render();
},
render: function (){
var self = this;
$(this.el).append("<a id='more'>Show more</a>");
$(this.el).append("<div id='show' style='display: none'>Div12</div>");
return this;
},
more: function (){
$('#more').text('Hide more');
$('#more').attr('id', '#hide');
$('#show').show();
},
less: function (){
$('#hide').text('Show more');
$('#show').hide();
},
});
干杯
最佳答案
你这里有很多问题。
您正在尝试将事件绑定(bind)到不存在的 hide
方法,你的events
应该是这样的:
events: {
'click #more': 'more',
'click #hide': 'less',
},
你的 initialize
方法正在尝试绑定(bind)一个方法,next
,这是不存在的。你的initialize
应该看起来更像这样:
initialize: function (){
_.bindAll(this, 'render', 'more', 'less');
this.render();
},
你的 more
方法是设置 id
至 #hide
但应该是hide
:
more: function (){
$('#more').text('Hide more').attr('id', 'hide');
$('#show').show();
},
你的 less
方法不会切换 id
返回more
:
less: function (){
$('#hide').text('Show more').attr('id', 'more');
$('#show').hide();
}
在 less
之后有一个逗号这会让一些浏览器不高兴。
演示:http://jsfiddle.net/ambiguous/8HkdT/
交换 id
这样的属性有点狡猾。您最好使用与 <div>
一起显示和隐藏的单独链接或者只是一个同时显示和隐藏的切换按钮。
关于javascript - 使用 Backbone.js 显示 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344119/