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

在滚动回调内部,thiswindow元素而不是您的$mandarina对象。您需要保存对$mandarinavia 的引用;

onScroll: function () {
    var that = this;

    $(window).scroll(function(e){
        var scrollTop = $(window).scrollTop();
        if(scrollTop > that.header.height()){
            that.mainCnt.addClass('fixed-header');
        }else{
            that.mainCnt.removeClass('fixed-header');
        }
    });
}

...即存储thisin的值,并在事件处理程序中that使用that而不是使用。this

于 2013-05-16T10:04:48.953 回答
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 回答
-1
this.header.height

你需要删除this

于 2013-05-16T10:02:02.807 回答