jQuery插件获取未定义的值

jQuery插件获取未定义的值,jquery,jquery-plugins,Jquery,Jquery Plugins,我正在学习如何制作自己的jQuery插件,我遇到了一个问题,我不知道为什么我会看到这个问题。这是我的插件: (function($){ $.fn.clipping = function() { console.log("Offset Width: " + this.offsetWidth); console.log("Scroll Width: " + this.scrollWidth); if(this.offsetWidth >

我正在学习如何制作自己的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查看我希望它查看的确切元素?

在您的插件中,这是一个jQuery对象。您应该使用.prop来获取DOM属性:

this.prop('offsetWidth');
this.prop('scrollWidth');
插件的一个良好实践是循环初始jQuery对象,同时返回它以允许链接。在循环中,这将是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元素的对象