我有一个循环
$(".box").find('.video, .print, .web').closest('.box').each(function (index)
{
$(this).delay(100 * index).fadeIn(300);
});
这段代码很好用。但是我很多地调用了这三个类,我想把它变成一个变量。 EX:
var resetBoxClass = ".print .web .video";
$(".box").find('resetBoxClass').closest('.box').each(function (index)
{
$(this).delay(100 * index).fadeIn(300);
});
令我失望的是,我无法让这个工作......这只是愚蠢的语义?谁能解释一下为什么?
答案 0 :(得分: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);
});
答案 1 :(得分:0)
尝试不带引号:
$(".box").find(resetBoxClass).etc(...
使用引号,您没有传入变量,而是传入字符串文字。
答案 2 :(得分:0)
在类之间的第一行添加逗号,并从find()
这是代码
var resetBoxClass = ".print, .web, .video";
$(".box").find(resetBoxClass).closest('.box').each(function (index)
{
$(this).delay(100 * index).fadeIn(300);
});
答案 3 :(得分:0)
您应该缓存元素而不是类来快速执行代码:
var yourTarget = $(".box").find('.video, .print, .web').closest('.box');
yourTarget.each(function (index)
{
$(this).delay(100 * index).fadeIn(300);
});
上面的代码执行得更快,因为你的元素已经被缓存了。
答案 4 :(得分: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 )
但我正在调用这三个类,我想把它变成一个变量。
你的意思是你也在代码的其他部分使用了那个选择器(问题中没有显示),对吧?对于问题中的代码片段,使用文字或变量将选择器传递给find()
并不重要。如果您在代码的其他部分使用相同的选择器,则使用变量将非常有用。我只是提到这个错误的机会,你错误地认为使用each()
循环意味着你“正在”调用那3个类别“。