Javascript 如何从具有相同类的多个元素中获取随机元素
我有一份名单,上面有一些虚假的销售通知。他们都有相同的班级。 使用我得到的代码,所有通知都会同时显示,但我每次只需要显示一个随机通知。我该怎么做 这是我目前的代码: PHP生成元素:Javascript 如何从具有相同类的多个元素中获取随机元素,javascript,jquery,html,Javascript,Jquery,Html,我有一份名单,上面有一些虚假的销售通知。他们都有相同的班级。 使用我得到的代码,所有通知都会同时显示,但我每次只需要显示一个随机通知。我该怎么做 这是我目前的代码: PHP生成元素: $notification .= ' <section class="custom-social-proof"> <div class="custom-notification">'; // Get fake sale notification info $specart
$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;
我发现你可以用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
中传递random,并隐藏所有被切换的同一类元素
请试一试。现在,您需要检测元素是否为alreay toggle
var len=$(“.custom social-proof”).length;
var random=0;
setInterval(函数(){
random=Math.floor(Math.random()*len);
$(“.custom social-proof”).hide('slow');
$(“.custom social-proof”).eq(random).stop().slideToggle('slow');
}, 1000);代码>
。定制社会证明{
显示:无;
}
1.
2.
3.
4.
5
非常乐意:)
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');
});