淡出文章并同时删除表格?

时间:2012-05-31 16:34:20

标签: jquery

我有一篇文章:

<article>
    Some paragraphs.
</article>

在下面,我有contact

<div id="contact">
    stuff, this form is 600 px tall
</div>

contact设置为display:none;

我使用jQuery来切换它。我要做的是从http://tutsplus.com/lesson/slides-and-structure/修改此脚本,以便淡出文章文本,然后在联系表单中滑动。遇到麻烦。

代码:

<script>

(function() {

$('html').addClass('js');

var contactForm = {

    container: $('#contact'),
    article: $('article'),

    init: function() {
        $('<button></button>', {
            text: 'Contact Me'
        })
            .insertAfter('article:first')
            .on('click', function() {
                console.log(this);
                this.show();
                // contactForm.article.fadeToggle(300);
                // contactForm.container.show();
            })
    },

    show: function() {
        contactForm.close.call(contactForm.container);
        contactForm.container.slideToggle(300);
    },

    close: function() {
        console.log(this);
        $('<span class=close>X</span>')
            .prependTo(this)
            .on('click', function(){
                contactForm.article.fadeToggle(300);
                contactForm.container.slideToggle(300);
            })
    }
};

contactForm.init();

})();

</script>

不起作用的部分是:

.on('click', function() {
    console.log(this);
    this.show();
    // contactForm.article.fadeToggle(300);
    // contactForm.container.show();
})

当我执行.on('click', this.show);时它工作正常,当我将this.show放入函数中时它不起作用!

1 个答案:

答案 0 :(得分:1)

this.show()close()内工作得很好,因为thisclose()范围内,但在.on('click') callback function范围内不可用,所以你需要保留this的引用,如下所示,并重复使用。

 close: function() {
        // keeping reference
        var reference = this;

        $('<span class=close>X</span>')
            .prependTo(this)
            .on('click', function(){
                //  using above reference here
                reference.article.fadeToggle(300);
                reference.container.slideToggle(300);
            })
    }