将字符串转换为要在jQuery.animate中使用的变量名

Convert string to variable name to use in jQuery .animate

本文关键字:变量名 animate jQuery 转换 字符串      更新时间:2023-09-26

这应该很容易,但我找不到答案。

我在变量中存储了五个位置值:navA、navB、navC等。

当用户点击一个链接时,我希望动画化地将div移动到那个位置:

$('myDiv').animate({
    'left': navB
},2000);

这是有效的。然而,当用户点击链接时,我收到的只是第一个字母——我需要在字母前面加上"nav",以获得navA或navB等

如何创建变量名称,并在animate函数中使用它?

我试过了:

$('theLink').click(function(){
    var nextLoc = $(this).attr('id').charAt(0); //returns A or B or C or...
    var nextVar = 'nav'+nextLoc;
    $('myDiv').animate({
        'left': nextVar
    },2000);
});

您可以使用窗口对象访问全局变量

var nextVar = window['nav'+nextLoc];

您还可以使用javascript的eval方法。。

var nextVar = eval('nav'+ nextLoc);