通过组合 string & 来创建新的 JavaScript 变量多变的
所以这是我的问题。
pageTitle1 = ('This is page one');
pageTitle2 = ('This is page two');
pageTitle3 = ('This is page three');
currentPageTitle = ('pageTitle'+currentPosition);
$("#pageNumber").html(currentPageTitle);
我试图根据我所在幻灯片的 currentPosition 在屏幕上显示当前页面标题。我遇到的问题是,当我需要显示“这是第一页”时,上面的代码在屏幕上显示“pageTitle1”。我对 javascript 很陌生,所以我感觉这是一个简单的解决方案,但几天的谷歌搜索并没有给我带来任何结果。
So this is my 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用数组而不是单独命名每个变量。
您的代码不起作用的原因是它只是添加两个字符串
"pageTitle"
和currentPosition
并将连接的字符串分配给currentPageTitle
。相反,您想要的是获取存储在具有该名称的变量中的值。假设您在全局范围内创建这些(顺便说一句,这不是一件好事),您可以这样做:但是,使用数组是更好的方法。
Use an array instead of naming each variable individually.
Reason why your code is not working is because it is simply adding the two strings
"pageTitle"
andcurrentPosition
and assigning the concatenated string tocurrentPageTitle
. 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:However, going with arrays is a better approach.
做这样的事情。
或者简单地使用 eval (真的超级不推荐)
Do something like this.
Or simply use eval (really super unrecommended)
无需任何其他修改,您可以将此行替换
为:
Without any other modifications, you can replace this line
with this: