首頁  >  問答  >  主體

每60秒為多個元素添加隨機的div類別值

我有一個頁面看起來像這樣:

<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>

我想知道是否有一種方法可以隨機插入一個div class為"percentx"(1-100之間的隨機數),這樣當頁面加載時,它會看起來像:

<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>
      <div class="percent75"></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>
      <div class="percent61"></div>

然後每60秒更改一次:

<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>
      <div class="percent21"></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>
      <div class="percent95"></div>

關於這個主題:

$('.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>

老實說,我不知道如何修改這段程式碼以滿足我的需求,任何幫助將不勝感激。

P粉342101652P粉342101652365 天前550

全部回覆(1)我來回復

  • P粉331849987

    P粉3318499872023-09-21 14:41:32

    看一下你提供的程式碼片段,你可以使用$('div[class*="percent"]')來選擇包含子字串'percent'的類別名稱。如果你希望每個div的隨機百分比是唯一的,我建議使用ID名稱。否則,下面的解決方案將每60秒覆蓋包含'percent'的所有類名,並將其替換為'percentx',其中x是隨機產生的數字。希望這能幫到你!

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

    回覆
    0
  • 取消回覆