this.attribute在构造之后没有定义

this.attribute is not defined after being constructed

本文关键字:定义 之后 attribute this      更新时间:2023-09-26

嗨,我做了一个非常小的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函数中的这个.header确实存在。。

在滚动回调中,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

尝试这个

$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();
});
this.header.height

您需要删除this