JQuery 插件中的 this.selector - 无法读取未定义的 属性 'top'
this.selector in JQuery plugin - Cannot read property 'top' of undefined
我见过很多关于此错误的问题,none 其中对这种情况很有帮助。
我正在尝试编写 JQuery 插件,但出现错误 "Uncaught TypeError: Cannot read property 'top' of undefined"。似乎与 "this" 有关。例如,这似乎工作正常:
$(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",但都没有成功。
谢谢
您已将 $(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();
希望这对您的案例有所帮助
我见过很多关于此错误的问题,none 其中对这种情况很有帮助。
我正在尝试编写 JQuery 插件,但出现错误 "Uncaught TypeError: Cannot read property 'top' of undefined"。似乎与 "this" 有关。例如,这似乎工作正常:
$(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",但都没有成功。 谢谢
您已将 $(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();
希望这对您的案例有所帮助