Javascript 如何使jQuery插件中的设置(或选项)可用于所有方法?
我已经使用jQuery几个月了(我仍然是Mootools的信徒),现在我正尝试在jQuery中创建我的第一个插件 问题是,我希望在我的插件中有一些方法,我希望这些方法能够访问插件的所有“属性” 例如:Javascript 如何使jQuery插件中的设置(或选项)可用于所有方法?,javascript,jquery,Javascript,Jquery,我已经使用jQuery几个月了(我仍然是Mootools的信徒),现在我正尝试在jQuery中创建我的第一个插件 问题是,我希望在我的插件中有一些方法,我希望这些方法能够访问插件的所有“属性” 例如: (function( $ ) { $.fn.test= function(method) { var settings; init: function() { var _defaults = {
(function( $ ) {
$.fn.test= function(method) {
var settings;
init: function() {
var _defaults = {
option1: 'value1',
option2: 'value2',
option3: 'value3',
url: 'default.php'
};
settings = $.extend({}, _defaults, method);
},
load: function(){
$.ajax({
cache : false,
type : "GET",
url : settings.url,
dataType: "json",
success : function(response){
console.log(response);
},
error : function(response) {
alert("Error loading data.");
}
});
}
}
}( jQuery ));
现在,对于插件本身的调用:
//初始化
$('#box1')。测试({
url:'另一个url.php'
});
问题是,当我调用“load”时,settings.url等于“default.php”,而不是“other url.php”
是否可以像在OOP中那样处理这个问题,我的意思是,将“设置”作为“类”的属性,然后对该属性的所有更改都是持久的
我希望在伪代码中实现的功能:
Class Test{
// Specify default settings
private settings = // some default values;
// Constructor
public Test(specificSettings){
//Code to merge/update specificSettings with settings
}
public load(){
// If I access this.settings in here, I will get the
// updated settings and not the default one
}
}
这也将允许我根据需要拥有尽可能多的“实例”,每个实例都有自己的设置值
提前感谢:)因此根据您的插件结构,您必须调用第一个init方法 因为当您调用$(“…”).test('load')时,它不会调用init函数,所以它将采用第一次声明的默认url
因此,根据插件结构,您必须调用第一个init方法 因为当您调用$(“…”).test('load')时,它不会调用init函数,所以它将采用第一次声明的默认url
你试过我的回答吗?你好@KevalBhatt!它工作得很好。非常感谢你!你们知道如何接受答案吗?你们试过我在答案中给出的吗?你好@KevalBhatt!它工作得很好。非常感谢你!你知道如何接受答案
Class Test{
// Specify default settings
private settings = // some default values;
// Constructor
public Test(specificSettings){
//Code to merge/update specificSettings with settings
}
public load(){
// If I access this.settings in here, I will get the
// updated settings and not the default one
}
}
(function( $ ) {
$.fn.test= function(method) {
var settings;
**init();** // call internally
init: function() {
var _defaults = {
option1: 'value1',
option2: 'value2',
option3: 'value3',
url: 'default.php'
};
settings = $.extend({}, _defaults, method);
},......