1

我有一个循环

$(".box").find('.video, .print, .web').closest('.box').each(function (index)
 {
     $(this).delay(100 * index).fadeIn(300);
 });

这段代码工作得很好。但是我经常调用这 3 个类,我想把它放入一个变量中。前任:

var resetBoxClass = ".print .web .video";

$(".box").find('resetBoxClass').closest('.box').each(function (index)
 {
     $(this).delay(100 * index).fadeIn(300);
 });

令我失望的是,我无法让它工作......这只是愚蠢的语义?有人可以向我解释为什么吗?

4

5 回答 5

7

缺少逗号resetBoxClass = ".print, .web, .video"; & $(".box").find('resetBoxClass')应该是$(".box").find(resetBoxClass)

这会有所帮助,

休息如下:

var resetBoxClass = ".print, .web, .video";

$(".box").find(resetBoxClass).closest('.box').each(function (index)
 {
     $(this).delay(100 * index).fadeIn(300);
 });
于 2012-06-22T09:40:49.800 回答
0

不带引号试试:

$(".box").find(resetBoxClass).etc(...

使用引号,您没有传递变量,而是传递了字符串文字。

于 2012-06-22T09:41:31.960 回答
0

在类之间的第一行添加逗号,并从find()

这是代码

var resetBoxClass = ".print, .web, .video";

$(".box").find(resetBoxClass).closest('.box').each(function (index)
{
     $(this).delay(100 * index).fadeIn(300);
});
于 2012-06-22T09:43:34.180 回答
0

你应该需要缓存你的元素而不是类来快速执行你的代码:

var yourTarget = $(".box").find('.video, .print, .web').closest('.box');

yourTarget.each(function (index)
 {
     $(this).delay(100 * index).fadeIn(300);
 });

上面的代码将执行得更快,因为您的元素已经被缓存。

于 2012-06-22T10:08:32.207 回答
0

@Tats_innit 回答了你的实际问题,所以我不会重复。

这是一个有点笨拙的结构:

$( ".box" ).find( ".video, .print, .web" ).closest( ".box" )

// or

$( ".box" ).find( resetBoxClass ).closest( ".box" )

您应该可以这样做:

$( ".box" ).has( ".video, .print, .web" )

// or

$( ".box" ).has( resetBoxClass )

但是我经常调用这 3 个类,我想把它放入一个变量中。

您的意思是您也在代码的其他部分(问题中未显示)中使用该选择器,对吗?对于您问题中的代码片段,您是否将选择器传递给find()使用文字或变量并不重要。如果您在代码的其他部分使用相同的选择器,则使用变量将是有益的。我只是在您错误地认为使用each()循环意味着您“大量调用这 3 个类”时才提到这一点。

于 2012-06-22T11:46:10.820 回答