简体   繁体   English

在jQuery插件扩展内访问this.element时遇到问题

[英]Problems accessing this.element inside jQuery plugin extension

I'm trying to extend upon an existing jQuery plugin and I've run into some problem, that has been discussed before, unfortunately not perfectly related to my case. 我正在尝试扩展现有的jQuery插件,但是遇到了一个之前已经讨论过的问题,不幸的是,与我的情况并不完全相关。 Basically, my code does something like this 基本上,我的代码做了这样的事情

(function($) {
    var self = $.ech.multiselect.prototype,
        orig_create = self._create,
        orig_init = self._init;
    var extensionMethods = {
        elemental: null,
        tooltip: function(e){
            var id = self.elemental.attr("id");
            //code
        },
        _create: function() {
            var ret = orig_create.apply(this, arguments);
            //code
            return ret;
        },
        _init: function() {
            var ret = orig_init.apply(this, arguments);
            this.elemental = this.element;
            return ret;
        },
        _bindEvents: function() {
            self.tooltip(e);
        }
    };

    $.extend(true, self.options, {tooltip: true});
    $.extend(true, self, extensionMethods);

})(jQuery);

My problem is I'm trying to store a reference to this.element inside the "elemental" object, so that I can use it to get the id of the control inside tooltip(). 我的问题是我试图将对this.element的引用存储在“ elemental”对象中,以便可以使用它来获取tooltip()中控件的ID。 It doesn't work, however and I've almost given up. 它不起作用,但是我几乎放弃了。

You're using self , which is the prototype object itself. 您正在使用self ,这是原型对象本身。 You want this , which refers to the instance and has the correct property: 您需要this ,它引用实例并具有正确的属性:

tooltip: function(e){
    var id = this.elemental.attr("id");
},

and: 和:

_bindEvents: function() {
    this.tooltip(e);
}

The elemental in the prototype should never be set, because the elements differ per instance. 原型中的elemental永远都不要设置,因为每个实例的元素都不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM