jQuery 插件获取未定义的值
jQuery plugin getting undefined values
我正在学习如何制作自己的 jQuery 插件,但我 运行 遇到了一个问题,我不确定为什么会看到这个问题。这是我的插件:
(function($){
$.fn.clipping = function() {
console.log("Offset Width: " + this.offsetWidth);
console.log("Scroll Width: " + this.scrollWidth);
if(this.offsetWidth > this.scrollWidth) {
} else {
}
};
})( jQuery );
然后在文档加载时我有这个:
$("#tiles").clipping();
在控制台中我得到这个:
Offset Width: undefined
Scroll Width: undefined
为什么会这样?我需要做些什么来确保它正在按我想要的 ID 查看确切的元素吗?
在您的插件中,this
是一个 jQuery 对象。您应该使用 .prop
来获取 DOM 属性:
this.prop('offsetWidth');
this.prop('scrollWidth');
插件的一个好的做法是循环初始 jQuery 对象,同时返回它以允许链接。在循环内部,this
将是 DOM 元素。
(function($){
$.fn.clipping = function() {
return this.each(function(){
console.log("Offset Width: " + this.offsetWidth);
console.log("Scroll Width: " + this.scrollWidth);
if(this.offsetWidth > this.scrollWidth) {
} else {
}
});
};
})( jQuery );
并且您的插件可以处理包含许多 DOM 元素的对象。
我正在学习如何制作自己的 jQuery 插件,但我 运行 遇到了一个问题,我不确定为什么会看到这个问题。这是我的插件:
(function($){
$.fn.clipping = function() {
console.log("Offset Width: " + this.offsetWidth);
console.log("Scroll Width: " + this.scrollWidth);
if(this.offsetWidth > this.scrollWidth) {
} else {
}
};
})( jQuery );
然后在文档加载时我有这个:
$("#tiles").clipping();
在控制台中我得到这个:
Offset Width: undefined
Scroll Width: undefined
为什么会这样?我需要做些什么来确保它正在按我想要的 ID 查看确切的元素吗?
在您的插件中,this
是一个 jQuery 对象。您应该使用 .prop
来获取 DOM 属性:
this.prop('offsetWidth');
this.prop('scrollWidth');
插件的一个好的做法是循环初始 jQuery 对象,同时返回它以允许链接。在循环内部,this
将是 DOM 元素。
(function($){
$.fn.clipping = function() {
return this.each(function(){
console.log("Offset Width: " + this.offsetWidth);
console.log("Scroll Width: " + this.scrollWidth);
if(this.offsetWidth > this.scrollWidth) {
} else {
}
});
};
})( jQuery );
并且您的插件可以处理包含许多 DOM 元素的对象。