Make new JavaScript variable by combining string & variable
So this is m开发者_StackOverflowy problem.
pageTitle1 = ('This is page one');
pageTitle2 = ('This is page two');
pageTitle3 = ('This is page three');
currentPageTitle = ('pageTitle'+currentPosition);
$("#pageNumber").html(currentPageTitle);
I'm trying to display the current page title to the screen based on the currentPosition of the slide I am on. The issue I'm having is the code above is displaying "pageTitle1" to the screen when I need it to display "This is page one". I'm newish to javascript so I have a feeling this an easy fix but days of googling has yielded me nothing.
Use an array instead of naming each variable individually.
var pageTitles = [
'This is page one',
'This is page two',
'This is page three'
];
var currentPageTitle = pageTitles[currentPosition];
Reason why your code is not working is because it is simply adding the two strings "pageTitle"
and currentPosition
and assigning the concatenated string to currentPageTitle
. What you instead want is to get the value stored in the variable having that name. Assuming you are creating these in the global scope (which is not a good thing btw), you can do:
var currentPageTitle = window['pageTitle'+currentPosition];
However, going with arrays is a better approach.
Do something like this.
var pageTitle = new Array();
pageTitle.push('This is page one');
pageTitle.push('This is page two');
pageTitle.push('This is page three');
currentPageTitle = (pageTitle[currentPosition]);
$("#pageNumber").html(currentPageTitle);
Or simply use eval (really super unrecommended)
var currentPageTitle = eval('pageTitle'+currentPosition);
Without any other modifications, you can replace this line
currentPageTitle = ('pageTitle'+currentPosition);
with this:
currentPageTitle = window['pageTitle'+currentPosition];
精彩评论