2

我开始使用 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();
    },

});

干杯

4

2 回答 2

5

你这里有很多问题。

您正在尝试将事件绑定到不存在的hide方法,您events应该如下所示:

events: {
    'click #more': 'more',
    'click #hide': 'less',
},

您的initialize方法正在尝试绑定一个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方法不会切换idmore

less: function (){
    $('#hide').text('Show more').attr('id', 'more');
    $('#show').hide();
}

而且你有一个杂散的逗号,之后less会让一些浏览器不开心。

演示:http: //jsfiddle.net/ambiguous/8HkdT/

像这样交换id属性有点狡猾。您最好使用显示和隐藏的单独链接以及显示和隐藏<div>的单个切换按钮。

于 2012-02-18T21:46:52.110 回答
2

骨干源代码说:

// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.

您的代码说:el: $('body'),但足以说明el: 'body'

从 Backbone 0.9 开始,您可以使用this.$el代替$(this.el)

http://documentcloud.github.com/backbone/#View-$el

你可能想写'click #hide': 'less'而不是'click #hide': 'hide'.

于 2012-02-18T21:43:00.687 回答