I am stumped by a problem which i'd assume is a common Jquery occurence, but i've no idea how to fix!
I have 5 variables -
var pubtimed
var toolstimed
var newstimed
var mylinkstimed
var partnerstimed
Which are used to store on and off states.
I then have a script that checks cookies for recent states and updates the variables accordingly, then forwards the details onto a render function -var map = {
'pub': $.cookie('nwphportal_tabExpPub'),
'tools': $.cookie('nwphportal_tabExpTools'),
'news': $.cookie('nwphportal_tabExpNews'),
'mylinks': $.cookie('nwphportal_tabExpLinks'),
'partners': $.cookie('nwphportal_tabExpPartners')
}
$.each(map, function (key, value) {
if (value != null) {
var varname = key + 'timed';
varname = value;
renderScrn(varname)
} else {
var varname = key + 'timed';
varname = "1"
renderScrn(varname)
}
});
The problem I have is that I want the variable varname to be trea开发者_JAVA技巧ted as each of the 5 variables above (e.g. key plus timed = pubtimed). But this doesnt happen and I just get an error. I could just place a list of if statements to fix this, but wondered if there were a better solution?
Please help if you can!
Cheers for your time. Paul
I would go for namespacing, encapsulating the related data into one object:
var timed = {};
$.each(map, function (key, value) {
if (value != null) {
timed[key] = value;
renderScrn(varname);
}
else {
timed[key] = 1;
renderScrn(varname);
}
});
So you can call them timed.partners
, timed.pub
, and so on...
If they're global variables, you can do this:
window[key + 'timed'] = value;
If they're not global (though they look so from what you posted), then you'll have to keep them in a container object, kind-of like your "map":
var container = {
pubtimed: null,
// ...
};
// ...
container[key + 'timed'] = value;
edit — as @galambalazs wrote in his answer, it'd be better to avoid doing this. If you set up a container, just use the keys directly.
精彩评论