这个问题应该很容易,但由于我是编程新手,尤其是javascript语言,所以我无法弄清楚。 假设我有以下javascript代码:
var InjectClientValue = Class.create();
InjectClientValue.prototype = {
initialize: function( sourceElement, eventElement, updateElement ) {
this.sourceElement = $(sourceElement);
this.element = $(eventElement);
this.updateElement =$(updateElement)
this.element.observe('click',this.onClick.bindAsEventListener(this));
},
onClick: function(event) {
new Ajax.Request(this.element.href+"/"+this.sourceElement.value, {
method:'get',
onSuccess: function(transport) {
//How do I access the instance variable updateElement in InjectClientValue_
//updateElement.update(transport.responseJSON.content);
}
});
event.stop();
}
}
我需要通过Ajax.Request的onSuccess访问initialize中的变量updateElement——该怎么办?
Try this:
onClick: function(event) {
var thisVariable = this;
new Ajax.Request(this.element.href+"/"+this.sourceElement.value, {
method:'get',
onSuccess: function(transport) {
thisVariable.updateElement.update(transport.responseJSON.content);
}
Since you already have an instance of the class as "InjectClientValue," you can use that to reference the object and call methods on it.
onClick: function(event) {
new Ajax.Request(this.element.href+"/"+this.sourceElement.value, {
method:'get',
onSuccess: function(transport) {
InjectClientValue.updateElement.update(transport.responseJSON.content);
}