gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:36:33 26 4
gpt4 key购买 nike

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

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

对此:

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

问题是 = $( '.'+thisClass ); 工作得很好,但 var $(thisClass) 不行。我尝试了一些变体,包括: var $thisClassvar $('thisClass') 但都不起作用。

是否可以插入/注入(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 );

最佳答案

您的问题在于范围。在您发布的代码中,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 对象。美元符号用作变量名称的一部分时没有任何意义。

关于javascript - 如何用变量替换 $a 中的 "a",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47861107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com