gpt4 book ai didi

javascript - 如何检测类(class)中的 child 人数?

转载 作者:行者123 更新时间:2023-11-28 05:18:54 25 4
gpt4 key购买 nike

我正在尝试创建一个无限循环的内容 slider 。我目前让它循环 3 个元素,但我想实现一个功能,让它始终循环而无需更新脚本。

我想知道的是,如果我可以创建一个 if 语句来表示“如果 x 大于 .quote 中的元素数,则执行此操作。”或者我必须将 .quote 分配给变量吗?

这是 JSFiddle

var x = 1;

$('.quote:nth-child(2)').hide();
$('.quote:nth-child(3)').hide();

$('#next').click(function(e){
e.preventDefault();

if(x === 3){
$('.quote:nth-child(' + x + ')').hide();
x = 1;
$('.quote:nth-child(' + x + ')').show();
}
else{
$('.quote:nth-child(' + x + ')').hide();
x++;
$('.quote:nth-child(' + x + ')').show();
}
});

$('#prev').click(function(e){
e.preventDefault();

if(x === 1){
$('.quote:nth-child(' + x + ')').hide();
x = 3;
$('.quote:nth-child(' + x + ')').show();
}
else{
$('.quote:nth-child(' + x + ')').hide();
x--;
$('.quote:nth-child(' + x + ')').show();
}
});

最佳答案

"If x is greater than the number of elements in .quote, do this." Or would I have to assign .quote to a variable?

没有变量

if (x > $('.quote').length) { do stuff... }

但您也可以将其分配给变量。这样效率更高,因为您不会不必要地一遍又一遍地执行长度计算 - 只要长度不变即可。

var quote = $('.quote').length;
if (x > quote) { do stuff... }

关于javascript - 如何检测类(class)中的 child 人数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682705/

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