我已经看到很多关于这个错误的问题,其中没有一个对这种情况非常有帮助。
我正在尝试编写一个JQuery插件,但是我收到错误“Uncaught TypeError:无法读取未定义的属性'top'”。似乎与“这个”有关。例如,这似乎工作正常:
$(window).scroll(function() {
var offsetBot = window.innerHeight - (($("#textBox1").offset().top - $(window).scrollTop()) + $("#textBox1").height());
console.log(offsetBot);
});
但是在下面的函数里面,我得到了错误..
$.fn.offBottom= function() {
$(window).scroll(function() {
if (!this.length) {
console.log("no element selected")
return;
} else{
var offsetBot = window.innerHeight - (($(this.selector).offset().top - $(window).scrollTop()) + $(this.selector).height());
}});
};
$("#textBox1").offBottom();
});
我尝试过使用“this”,“$(this)”和“this.selector”都没有运气。 感谢
答案 0 :(得分:1)
您已将$(this)
上下文置于$(window)
滚动功能中。这就是为什么你得到DOM的元素[undefined]因此你无法得到它的top
属性
您可能需要在此之前初始化DOM的元素:
$.fn.offBottom = function() {
var oElement = $(this); // $(this) will refer to the DOM that called the [offBottom] property method
$(window).scroll(function() {
if (oElement.length) {
console.log("no element selected");
return false;
} else {
console.log(oElement.offset().top);
var offsetBot = window.innerHeight - ((oElement.offset().top - $(window).scrollTop()) + $(this.selector).height());
}});
};
$("#textBox1").offBottom();
希望这有助于您的案例