大家好,我制作了一个非常小的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确实存在..
答案 0 :(得分:0)
在滚动回调中,this
是window
元素,而不是您的$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