【问题标题】:How to pass in this into jquery .change event [duplicate]如何将其传递给jquery .change事件[重复]
【发布时间】:2018-03-02 23:26:30
【问题描述】:

我正在编写一个自定义编辑器插件,我需要将 this 传递给 jquery .change 事件。我怎样才能使以下工作?

(function($R)
{
    $R.add('plugin', 'customplugin', {
        onmodal: {
            image: {
                open: function($modal, $form)
                {
                    this._load($modal)
                }
            }
        },
        _load: function($modal)
        {
            var $body = $modal.getBody();
            this.$box = $R.dom('<div>');

            this._getData('hello world'); //This works

            $('.item').change(function (this) { //'this' passed in here
                var value = $(this).val();

                this._getFoo(value); //This does not work

                return false;
            }).keyup(function () {
                $(this).change();
            });
        },
        _getFoo: function(param) {
            console.log('_getFoo() called with param ' + param);
        },
    });
})(Redactor);

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    在调用它之前只需将其值分配给另一个变量:

    var that = this;  // You can rename to what `this` represents here
    
    $('.item').change(function() {
      // Use `that` here, e.g.:
      that._getFoo(value);
    });
    

    替代解决方案:

    $('.item').change(function(e) {
      // Use `e.currentTarget` when you'd use `this` here before
      var value = $(e.currentTarget).val();
    
      // Use `this` to access parent scope's `this`, e.g.:
      this._getFoo(value);
    }.bind(this));
    

    或者使用 ES6+ 的箭头函数(未经测试,应该可以):

    $('.item').change(e => {
      // Use `e.currentTarget` when you'd use `this` here before
      var value = $(e.currentTarget).val();
    
      // Use `this` to access parent scope's `this`, e.g.:
      this._getFoo(value);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      相关资源
      最近更新 更多