【问题标题】:Access JQuery UI Widget from within Click callback function从 Click 回调函数中访问 JQuery UI Widget
【发布时间】:2016-08-20 11:45:45
【问题描述】:

单击时,我的 JQuery-UI 小部件应将 div 附加到自身。但是我的按钮回调无法访问this.element - 它是未定义的,因为我假设this 指的是按钮而不是我的小部件。请参阅下面的简单代码以获得更好的描述:

(function ($) {

  $.widget( "my.myWidget", {

        _create: function () {

            this.element.click(this.addRow);
        },

        addRow: function(evt) {

            // this.element is undefined?
            console.log("Is this.element defined: " + this.element != undefined);

            // cant append to this.element
            $('<div></div>')
                .appendTo(this.element);
        }
    });
})(jQuery);

如何在我的点击回调函数中访问小部件 (this.element)?

【问题讨论】:

    标签: javascript jquery jquery-ui


    【解决方案1】:

    它不起作用的原因是this.element.click 侦听器回调是从不同的范围内调用的。因此,addRow 中的范围不是小部件。

    有两种方法可以解决这个问题。

    选项 1:通过将 this 存储在变量中,以便您可以从另一个范围内访问它。例如:

    (function ($) {
        $.widget( "my.myWidget", {
    
            _create: function () {
                var self = this;
                this.element.click(function() {
                    self.addRow();
                });
            },
    
            addRow: function(evt) {
    
                // this.element is undefined?
                console.log("Is this.element defined: " + this.element != undefined);
    
                // cant append to this.element
                $('<div></div>')
                        .appendTo(this.element);
            }
        });
    })(jQuery);
    

    选项 2:通过将 this 范围绑定到 this.addRow 函数对象:

    (function ($) {
    
        $.widget( "my.myWidget", {
    
            _create: function () {
                this.element.click(this.addRow.bind(this));
            },
    
            addRow: function(evt) {
    
                // this.element is undefined?
                console.log("Is this.element defined: " + this.element != undefined);
    
                // cant append to this.element
                $('<div></div>')
                        .appendTo(this.element);
            }
        });
    })(jQuery);
    

    【讨论】:

      【解决方案2】:

      您应该声明另一个 this 对象以在回调中使用它:

      var _this = this;
      

      在你的小部件类的第一行定义它。

      【讨论】:

      • 您能详细说明具体在哪里吗?它是否应该高于_create: ...,因为这会产生编译器错误(因为它在地图/对象中)。具体在哪里?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多