0

I'm learning javascript. I want to try creating a simple object for hiding/showing some blocks of text, so I wrote this code.

   var Post = {
    init: function(el){
        this.el = el;
        this.title = el.children(".title");
        this.entry = el.children(".entry");
        var that = this;
        this.title.on("click", function(){
            that.hide();
        });

    },
    hide: function(){
        this.entry.slideUp('fast');
    },
    show: function(){
        this.entry.slideDown('fast');
    }
}
$(".post").each(function(){
    Post.init($(this));
})

http://jsfiddle.net/ZVpau/

And the problem is, that this code is always hiding only last post, no matter what title you have clicked on. Can anyone tell me where is the problem?

4

1 回答 1

2

您只有一个 Post 对象,并且它只包含一个元素。
为每个元素创建一个对象。为此,您可以使用构造函数

function Post(el){
    this.el = el;
    this.title = el.children(".title");
    this.entry = el.children(".entry");
    var that = this;
    this.title.on("click", function(){
        that.hide();
    });

    this.hide = function(){
        this.entry.slideUp('fast');
    };
    this.show = function(){
        this.entry.slideDown('fast');
    }
}
$(".post").each(function(){
    new Post($(this));
})

http://jsfiddle.net/ZVpau/1/

于 2013-09-07T16:22:21.393 回答