Jquery 插件和 $.ajax
我正在尝试编写一个基于原型模式的 jQuery 插件。
我的问题是,当我使用 $.ajax
函数加载 xml 文件时,我丢失了 this
对象。
例如这项工作:
Plugin.prototype = {
defaults: {
message: 'Hello world!'
},
init: function() {
this.setStyleAndOptions();
return this;
},
setStyleAndOptions: function() {
alert("setStyleAndOptions : ");
}
}
但事实并非如此,我收到一条错误消息“this.setStyleAndOptions 未定义”:
Plugin.prototype = {
defaults: {
message: 'Hello world!'
},
init: function() {
$.ajax({
type: "GET",
url: "param.xml",
dataType: "xml",
success: this.initOptions
});
return this;
},
initOptions: function(dataxml) {
// Error occured here, I suppose "this" is not the plugin anymore
this.setStyleAndOptions();
},
setStyleAndOptions: function() {
alert("setStyleAndOptions");
}
}
感谢您的帮助。
I'm trying to do write a jQuery plugin based on a prototype pattern.
My problem is when I use the $.ajax
function to load an xml file, I loose the this
object.
For example this work :
Plugin.prototype = {
defaults: {
message: 'Hello world!'
},
init: function() {
this.setStyleAndOptions();
return this;
},
setStyleAndOptions: function() {
alert("setStyleAndOptions : ");
}
}
But that doesn't, I get an error saying "this.setStyleAndOptions is not defined" :
Plugin.prototype = {
defaults: {
message: 'Hello world!'
},
init: function() {
$.ajax({
type: "GET",
url: "param.xml",
dataType: "xml",
success: this.initOptions
});
return this;
},
initOptions: function(dataxml) {
// Error occured here, I suppose "this" is not the plugin anymore
this.setStyleAndOptions();
},
setStyleAndOptions: function() {
alert("setStyleAndOptions");
}
}
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将
this
存储在变量中:Try storing
this
in a variable:问题是
this
是错误发生时的函数。您可以使用 apply 或 call 函数尝试:The problem is that
this
is the function on the moment of the error. You could try it with the apply or call function: