You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现每60秒为多元素随机添加percentX类及父元素样式切换

问题与解决方案

初始需求

用户页面结构如下:

<a href="#" onclick="go('register')">
      <img class="img" src="img/192.webp" alt="box set" />
      <div class="name" style="line-height: 2">box set</div>
    </a>
  </div>
  <div class="item ">
    <a href="#" onclick="go('register')">
      <img class="img" src="img/182.webp" alt="battery" />
      <div class="name" style="line-height: 2">battery</div>

需要实现:

  • 页面加载时,在每个<a>标签内插入class为percentX(X为1-100随机数)的<div>
  • 每60秒更新该div的class(重新生成随机数X)

参考代码:

$('.percent').each(function () {
  var x = Math.floor((Math.random() * 100) + 1);
  $(this).text(x)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="percent"></div>

更新后的问题

用户修改代码后,补充需求:

  • 随机数x<50时,对应<a>标签保持class="items"
  • 随机数x>50时,对应<a>标签改为class="items hot"并添加<img class="overlay-img" src="css/img/logo-hot.gif">

当前HTML代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="percent"></div>
<div id="pp" class="group_flex">
<a class="items " href="#" onclick="go('daftar')"><img loading="lazy" class="gimg" src="img/18.webp" alt="Jagung" />  <div class="gname">Jagung</div><div class="percent52"></div></a>
<a class="items " href="#" onclick="go('daftar')"><img loading="lazy" class="gimg" src="img/77.webp" alt="Semangka" />  <div class="gname">Semangka</div><div class="percent44"></div></a>
<a class="items " href="#" onclick="go('daftar')"><img loading="lazy" class="gimg" src="img/109.webp" alt="Nanas" />  <div class="gname">Nanas</div><div class="percent59"></div></a>
</div>

当前JS代码:

function additems(){
    document.getElementById('pp').className = 'items ';
}
function addhot(){
document.getElementById('pp').setAttribute( "class", "items hot" );
// need some code to add <img class="overlay-img" src="css/img/logo-hot.gif" >
}
  
setInterval(function() {
    $('div[class*="percent"]').each(function () {
            var x = Math.floor((Math.random() * 100) + 1);
            if (x < 50 ){
            $(this).attr('class', 'percent' + x);
            additems()
            } else {
            addhot()
         }    
    });
}, 2000);

遇到的问题:

  • 仅修改group_flex下第一个子元素
  • x<50时有时也会切换为items hot

解决方案

问题根源

  1. additems和addhot操作的是父容器#pp,而非每个<a>标签,导致所有项受最后一次操作影响。
  2. 循环中每次调用additems/addhot会覆盖之前的修改,最终结果由最后一个元素的随机数决定。

修改后的JS代码

// 处理单个项的状态更新
function updateItemStatus($percentDiv, x) {
    // 获取当前percent对应的a标签
    const $aTag = $percentDiv.closest('a.items');
    if (!$aTag.length) return;

    // 更新percent的class
    $percentDiv.attr('class', `percent${x}`);

    if (x < 50) {
        // 移除hot类,保留items
        $aTag.removeClass('hot');
        // 删除已有的overlay图片
        $aTag.find('.overlay-img').remove();
    } else {
        // 添加hot类
        $aTag.addClass('hot');
        // 检查是否已有overlay图片,避免重复添加
        if (!$aTag.find('.overlay-img').length) {
            $aTag.append('<img class="overlay-img" src="css/img/logo-hot.gif" alt="hot">');
        }
    }
}

// 页面加载完成后初始化所有项
$(document).ready(function() {
    $('div[class*="percent"]').each(function() {
        const randomNum = Math.floor(Math.random() * 100) + 1;
        updateItemStatus($(this), randomNum);
    });
});

// 每60秒更新一次(原代码2秒可按需调整)
setInterval(function() {
    $('div[class*="percent"]').each(function() {
        const randomNum = Math.floor(Math.random() * 100) + 1;
        updateItemStatus($(this), randomNum);
    });
}, 60000);

核心优化点

  • 使用closest('a.items')定位当前percent对应的<a>标签,确保每个项独立处理。
  • 封装状态更新逻辑到函数,避免重复代码且逻辑更清晰。
  • 添加overlay图片前先检查是否存在,防止重复插入。
  • 页面加载时执行初始化,满足加载时的需求。
  • 调整定时器为60000毫秒(60秒),匹配最初需求。

内容的提问来源于stack exchange,提问作者Atms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:42:02