我想创建一系列变量,如下所示,每个变量都有设置:
var panel_myfeed = new Array();
panel_myfeed[0]="/myfeed";
panel_myfeed[1]="#view-panel-myfeed";
panel_myfeed[2]="XXXXXXXX";
var panel_OtherPanel = new Array();
panel_OtherPanel[0]="/otherurl";
panel_OtherPanel[1]="#other-url-panel";
var panel_OtherPanel2 = new Array();
panel_OtherPanel2[0]="/otherurl2";
panel_OtherPanel2[1]=".other-url-panel2";
然后我想要两个可以使用这些变量的单独函数
function WhichPanel(url) {
*** Given a URL var like /myfeed, which which panel[0] this belongs to so I can get the other variables
** do something now that I have the settings above
}
function KillPanel(url) {
*** Given a URL var like /myfeed, which which panel[0] this belongs to so I can get the other variables
** do something now that I have the settings above
}
连连呢? thxs
答案 0 :(得分:2)
这里的对象地图最简单,如下所示:
var panels = { "/myfeed": "#view-panel-myfeed",
"/otherurl": "#other-url-panel",
"/otherurl2": ".other-url-panel2" }
然后在你的函数中你可以panels[url]
来获取随之而来的选择器。如果您需要其他属性,只需使用对象代替值:
var panels = { "/myfeed": { selector: "#view-panel-myfeed", other: "value" },
"/otherurl": { selector: "#other-url-panel" },
"/otherurl2": { selector: ".other-url-panel2" } }
然后要获取选择器,对于其他属性,它将是panels[url].selector
,.property
等。
答案 1 :(得分:1)
我建议使用JSON这样的对象:
var panels = {
'/myfeed': {
selector: "#view-panel-myfeed",
somevariable="XXXXXXXX"
},
'/otherurl': {
selector: "#other-url-panel"
},
'/otherurl2': {
selector: ".other-url-panel2"
}
}
然后你可以通过以下方式获得所有设置:
function WhichPanel(url) {
var settings = panels[url];
alert(settings.selector);
}
WhichPanel('/myfeed'); //should alert "#view-panel-myfeed"
答案 2 :(得分:1)
以这种方式处理数组变得非常困难;你必须记住索引代表什么。拥有一个有意义的属性名称的对象要好得多。
function SelectObj(id, clz) {
this.id = id;
this.clz = clz;
}
var objMap = {
"/myfeed": new SelectObj('#view-panel-myfeed', 'XXXXXX'),
"/otherurl": new SelectObj('#other-url-panel', null),
"/otherurl2": new SelectObj(null, '.other-url-panel2')
}
function WhichPanel(url) {
var obj = objMap[url];
// do something with obj.id and/or obj.clz
}
function KillPanel(url) {
var obj = objMap[url];
// do something with obj.id and/or obj.clz
}
这种方法的另一个优点是您可以向您的班级添加功能,例如:
SelectObj.prototype.buldSelector = function() {
var selector = '';
if(this.id) selector += this.id;
if(this.clz) selector += this.clz;
return selector;
}