2

こんにちは、私は非常に小さな jquery プラグインを作成しました。

$mandarina = {
    mainCnt: $('#main'),
    header: $('header.site-header'),
    init: function () {
        this.onScroll();
    },
    onScroll: function () {
        $(window).scroll(function(e){
            var scrollTop = $(window).scrollTop();
            if(scrollTop > this.header.height()){
                this.mainCnt.addClass('fixed-header');
            }else{
                this.mainCnt.removeClass('fixed-header');
            }
        });
    }
}
$(function () {
    $mandarina.init();
});

しかし、スクロールすると、コンソールに次のエラーが表示されます。

TypeError: this.header is undefined
[Parar en este error]   

if(scrollTop > this.header.height()){

理由はありますか?

奇妙なことは、それが存在する init 関数の this.header です..

4

3 に答える 3

0

これを試して

$mandarina = {
mainCnt: $('#main'),
header: $('header.site-header'),
init: function () {
    this.onScroll();
},
onScroll: function () {
    var $this= $(this);
    $(window).scroll(function(e){
        var scrollTop = $(window).scrollTop();
        if(scrollTop > $this.header.height()){
            $this.mainCnt.addClass('fixed-header');
        }else{
            $this.mainCnt.removeClass('fixed-header');
        }
    });
 }
}

$(function () {
    $mandarina.init();
});
于 2013-05-16T10:05:08.253 に答える