gpt4 book ai didi

javascript - 如何从具有相同类的多个元素中获取随机元素

转载 作者:行者123 更新时间:2023-11-27 22:52:47 25 4
gpt4 key购买 nike

我有一个包含一些假冒销售通知元素的列表。他们都有同一个类(class)。使用我得到的代码,所有通知都会同时显示,但我每次只需要显示 1 个随机通知。我该怎么做?

这是我目前的代码:

PHP 生成元素:

$notification .= '
<section class="custom-social-proof">
<div class="custom-notification">';
// Get fake sale notification info
$specarticles = '
SELECT
c.alias as content_alias,
c.title as content_title,
c.catid,
c.state,
c.featured,
c.images,
ca.id,
ca.published,
ca.title as cat_title,
ca.alias as cat_alias
FROM snm_content c
LEFT JOIN snm_categories ca
ON c.catid = ca.id
WHERE c.featured = 1
AND c.state = 1
AND ca.published = 1';
$specarticlescon = $conn->query($specarticles);
while($specarticles = $specarticlescon->fetch_assoc()){

$imagesjson = json_decode($specarticles['images']);

if(!empty($imagesjson->image_intro)){
$image = 'https://website.nl/cms/'.$imagesjson->image_intro;
}else{
$image = '';
}

$notification .= '
<div class="custom-notification-container">
<div class="custom-notification-image-wrapper">
<img src="'.$image.'">
</div>
<div class="custom-notification-content-wrapper">
<p class="custom-notification-content">
Piet De Graaf - Spijkenisse<br>reserveerde <a href="'.$specarticles['cat_alias'].'/'.$specarticles['content_alias'].'">'.$specarticles['content_title'].'</a>
<small>vandaag</small>
</p>
</div>
</div>';
}
$notification .= '
<div class="custom-close"></div>
</div>
</section>';

echo $notification;

还有我的jquery:

setInterval(function(){ tpj(".custom-social-proof").stop().slideToggle('slow'); }, 8000);
tpj(".custom-close").click(function() {
tpj(".custom-social-proof").stop().slideToggle('slow');
});

我发现你可以用 eq 随机得到一些东西。所以我尝试了以下方法:

var len = tpj(".custom-social-proof").length;
var random = Math.floor( Math.random() * len ) + 1;
setInterval(function(){ tpj(".custom-social-proof").eq(random).stop().slideToggle('slow'); }, 8000);
tpj(".custom-close").click(function() {
tpj(".custom-social-proof").stop().slideToggle('slow');
});

但这会阻止通知完全显示。我做错了什么?

最佳答案

您需要在 setInterval 中传递随机数并隐藏所有切换到同一类的元素。

请尝试。现在你需要检测元素是否已经切换。

var len = $(".custom-social-proof").length;
var random = 0;

setInterval(function(){
random = Math.floor( Math.random() * len ) ;
$(".custom-social-proof").hide('slow');
$(".custom-social-proof").eq(random).stop().slideToggle('slow');
}, 1000);
.custom-social-proof{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section class="custom-social-proof">1</section>
<section class="custom-social-proof">2</section>
<section class="custom-social-proof">3</section>
<section class="custom-social-proof">4</section>
<section class="custom-social-proof">5</section>

关于javascript - 如何从具有相同类的多个元素中获取随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499682/

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