如何用变量替换 $a 中的 "a"

How Replace "a" in $a with Variable

我正在尝试用变量替换函数中的字母 "a"。例如,更改为:

setInterval(function(){         
    var $a = $( '.a' ); 
});

对此:

var thisClass = 'a';
setInterval(function(){         
    var $(thisClass) = $( '.'+thisClass );  
});

问题是 = $( '.'+thisClass ); 工作正常,但 var $(thisClass) 不工作。我尝试了一些变体,包括:var $thisClassvar $('thisClass') 但 none 有效。

是否可以 insert/inject 一个变量来代替 $a 中的 "a"?

更新:

以下是我实际代码的当前状态。我确实意识到我可以简单地将 $a 替换为 $( '.a' ),这解决了我尝试使用 var 一次替换我的函数中使用的所有类名的一些问题。但是最后我仍然留下 getElementById("a"),如果我使用 getElementById("classVar")getElementById(classVar) 来代替,这将不起作用。

    setTimeout(function(){
        var classVar = 'a'; 
        $('.'+classVar).makisu( 'toggle' );
            $('.'+classVar).makisu({ 
                selector: 'dd',
                overlap: Math.random() * (.7 - .2) + .2,
                speed: Math.random() * (3 - .2) + .2
            });
    }, document.getElementById("a").childElementCount*universalBoxTime );

只要知道父对象,就可以通过属性名称访问它。

在你的例子中,看起来你的变量在全局范围内,所以你可以尝试从 window 对象访问它:

var thisClass = 'a';
setInterval(function(){         
    window['$' + thisClass] = $( '.'+thisClass );  
});

如果您只需要在 setInterval 函数中使用此变量,您可以使用 this 而不是 window:

var thisClass = 'a';
setInterval(function(){         
    this['$' + thisClass] = $( '.'+thisClass );  
});

你的问题出在范围上。在您发布的代码中,classVar 仅存在于 setTimeout 回调内部,不能在外部使用。在JavaScript中,您可以创建创建和调用其他函数的函数,因此您可以通过这种方式使您的代码更通用:

function do_the_thing($elements) {
    var delay = $elements.children().length * universalBoxTime;

    setTimeout(function() {
        $elements.makisu('toggle');
        $elements.makisu({ 
            selector: 'dd',
            overlap: Math.random() * (.7 - .2) + .2,
            speed: Math.random() * (3 - .2) + .2
        });
    }, delay);
}

do_the_thing($('.a'));
do_the_thing($('.b'));

我使用 $elements 而不是 elements 只是为了表明 $elements 是一个 jQuery 对象。美元符号用作变量名称的一部分时没有任何意义。