构造后未定义this.attribute

时间:2013-05-16 09:59:22

标签: javascript jquery plugins undefined

大家好,我制作了一个非常小的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确实存在..

3 个答案:

答案 0 :(得分:0)

在滚动回调中,thiswindow元素,而不是您的$mandarina对象。您需要通过;

保存对$mandarina的引用
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');
        }
    });
}

...即将this的值存储在that中,并在事件处理程序中使用that代替this

答案 1 :(得分: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();
});

答案 2 :(得分:-1)

this.header.height

您需要删除this