gpt4 book ai didi

javascript - 显示随机类

转载 作者:行者123 更新时间:2023-11-30 09:04:46 24 4
gpt4 key购买 nike

假设我有一些类:

<div class="something" style="display: none">Some text I would like to show</div>
<div class="something" style="display: none">Some text2 I would like to show</div>
<div class="something" style="display: none">Some text3 I would like to show</div>
<div class="something" style="display: none">Some text4 I would like to show</div>
<div class="something" style="display: none">Some text5 I would like to show</div>

而且我想每隔几秒显示一次随机类。我想伪代码应该是这样的:

    setInterval(function() {
$('.something').hide();
var rand_number = random(1, ('.something').length);
$('.something').array[rand_number].show();
}, 5000);

谢谢。

最佳答案

尽量避免过于频繁地评估 $('.something'):

setInterval(function() {
var $s = $('.something');
var r = Math.floor(Math.random() * $s.length);
$s.hide().eq(r).show();
}, 5000);

如果您知道元素列表在文档加载后不会改变,您可以进一步简化:

$(function() { // short-hand for document.ready
var $s = $('.something');
var count = $s.length;
setInterval(function() {
var r = Math.floor(Math.random() * count);
$s.hide().eq(r).show();
}, 5000);
});

关于javascript - 显示随机类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6020939/

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