Another newbie question that has me stuck badly.
I have three variables
var state1
var state2
var state3
I need to access one of them on a .click event depending on a property of the clicked object.
How do I access the correct variable? Basically I need to for the variable name by adding "state" and the correct number together.
I will update this post soon with some code in case it's needed.
var backstate1;
var backstate2;
var backstate3;
var currentFrame;
function hotspotHover(){
var currentElement = this;
var daName =this.name;
$("#hotspot" +daName).hover(
function() {
$("img.changeOutline").prop("src", currentElement.outlinesArray[currentFrame]);
$("#outlines").show();
},
function() {
$("#outlines").hide();
}
).click(function() {
var backstateLevelNumber = currentElement.backStateLevel; //not working
window['backstate'+ backstateLevelNumber]=currentFrame; //trying to set backstate+number to current frame variable
hoverClick(currentElement.defaultFrame);
checkReverse();
checkSeqLoop();
});
};
Jacob
79k24 gold badges159 silver badges245 bronze badges
asked Aug 2, 2012 at 3:03
Sony packman
8402 gold badges10 silver badges21 bronze badges
2 Answers 2
Using an array would solve your problem:
var states = [null, null, null];
Accessing them would then be: (Assuming currentStateId being the current state number)
var currentState = state[currentStateId] //Access state
And for setting:
states[currentStateId] = "State"; //Set State
Sign up to request clarification or add additional context in comments.
Comments
Add the states as an array:
var states = [ 'state1', 'state2'];
var stateNumber = 0;
var state = states[stateNumber];
answered Aug 2, 2012 at 3:05
Krycke
3,2061 gold badge19 silver badges21 bronze badges
4 Comments
Brad Koch
It could be a proper answer if restated.
Krycke
Sorry 'bout that. Tries to restate the answer.
Sony packman
What I still don't seem to grasp is how would I then declare a value for the state1 or state2? I'm trying to do basically this: If clicked object has statelevel==1 then modify the value of state1 to be currentFrame.
Krycke
Can't you use
window[ states[number] ] = currentFrame;lang-js
var state=[state1, state2, state3]and accessing them bystate[number]