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>表示と非表示の両方を行う、または1つのトグルボタンと一緒に表示と非表示を切り替える個別のリンクを使用することをお勧めします。

于 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'

this.$elまた、Backbone 0.9以降、次の代わりに使用できます$(this.el)

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

'click #hide': 'less'そして、あなたはおそらくの代わりに書きたいと思ったでしょう'click #hide': 'hide'

于 2012-02-18T21:43:00.687 に答える