Javascript 如何将其传递到jquery.change事件中
我正在编写一个自定义的redactor插件,我需要将其传递到jquery.change事件中。我怎样才能使以下各项发挥作用Javascript 如何将其传递到jquery.change事件中,javascript,jquery,oop,Javascript,Jquery,Oop,我正在编写一个自定义的redactor插件,我需要将其传递到jquery.change事件中。我怎样才能使以下各项发挥作用 (function($R) { $R.add('plugin', 'customplugin', { onmodal: { image: { open: function($modal, $form) { this._loa
(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);
在调用它之前,只需将其值赋给另一个变量:
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);
});