jQuery扩展,无法读取undefined的属性

时间:2014-08-25 23:20:40

标签: javascript jquery extend

我有这段代码:

var viewport = $(window),
    viewport_height = viewport.height();

var _topPanel = jQuery.extend({
    el: $('.js-lp_top'),
    //
    height: function() {
        var self = this;

        self.el.css('min-height', viewport_height);
    },
    scroll : function() {
        var self = this;
        var scrolled = viewport.scrollTop();

        viewport.on('scroll', function() {
            self.el.css({
                'top': (49 - (scrolled / viewport_height) * 80) + '%'
            });
        });
    }
});
var topPanel = new _topPanel.height().scroll();

jQuery错误Cannot read property 'css' of undefined。我做错了什么?求助。

1 个答案:

答案 0 :(得分:1)

让我们先来看看这行代码。

 var topPanel = new _topPanel.height().scroll();

关键字new会创建一个新的空对象。在height函数中,this关键字引用了这个新对象,当然它没有el属性。 self.el未定义,因此出现错误消息Cannot read property 'css' of undefined

这里有两个变化:

  1. 确保您的heightscroll函数返回this,以支持函数链

  2. 调用new函数时不要包含height关键字

  3. 以下是修改后的代码:

    var _topPanel = jQuery.extend({
        el: $('.js-lp_top'),
        //
        height: function () {
            var self = this;
    
            self.el.css('min-height', viewport_height);
            return self;
        },
        scroll: function () {
            var self = this;
            var scrolled = viewport.scrollTop();
    
            viewport.on('scroll', function () {
                self.el.css({
                    'top': (49 - (scrolled / viewport_height) * 80) + '%'
                });
            });
            return self;
        }
    });
    var topPanel = _topPanel.height().scroll();