-1

我想在这里创建一个我的里程表使用相同的类并且只声明一次。我试过了document.querySelectorAll('.odometer'),但它不起作用。请参阅下面的参考

到目前为止我尝试了什么:其他链接(http://jsfiddle.net/9hawxpne/

const elements = document.querySelectorAll('.odometer');
Array.from(elements).forEach((element, index) => {
  ticketOdometer = new Odometer({
    el: elements[index] ,
    minIntegerLen: 2,
    format: 'd',
    theme: 'digital',
    value: 40
  });
});




var odometer_bool_counter = true;

function setRandomOdometerValue() {
  if (odometer_bool_counter) {
    $('.odometer').html(Math.floor(Math.random() * (40 - 1 + 1) + 1)); // change value
  }
}
setInterval(function() {
  setRandomOdometerValue();
}, 2500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Odometr includes -->

<link rel="stylesheet" href="http://github.hubspot.com/odometer/themes/odometer-theme-digital.css" />
<script src="http://github.hubspot.com/odometer/odometer.js"></script>



<div id="odometer" class="odometer" style="font-size:72pt;">
  40
</div>
<div id="" class="odometer" style="font-size:72pt;">
  40
</div>
<div id="" class="odometer" style="font-size:72pt;">
  40
</div>
<div id="" class="odometer" style="font-size:72pt;">
  40
</div>
<div id="" class="odometer" style="font-size:72pt;">
  40
</div>

4

1 回答 1

1

setRandomOdometerValue函数中,您要更改每个.odometer.

由于您已经在使用 jQuery,因此您可以使用 jQuery 来执行此操作each

$('.odometer').each(function() {
  $(this).html(Math.floor(Math.random() * (40 - 1 + 1) + 1));
})

但你也可以只使用 javascript:

elements.forEach((element) => {
  element.innerHTML = Math.floor(Math.random() * (40 - 1 + 1) + 1)
});

const elements = document.querySelectorAll('.odometer');

Array.from(elements).forEach((element, index) => {
  ticketOdometer = new Odometer({
    el: elements[index] ,
    minIntegerLen: 2,
    format: 'd',
    theme: 'digital',
    value: 40
  });
});

function setRandomOdometerValue() {
  $('.odometer').each(function() {
    $(this).html(Math.floor(Math.random() * (40 - 1 + 1) + 1)); // change value
  })
}

setInterval(() => {
  setRandomOdometerValue();
}, 2500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Odometr includes -->
<link rel="stylesheet" href="http://github.hubspot.com/odometer/themes/odometer-theme-digital.css" />
<script src="http://github.hubspot.com/odometer/odometer.js"></script>

<div class="odometer">40</div>
<div class="odometer">40</div>
<div class="odometer">40</div>
<div class="odometer">40</div>
<div class="odometer">40</div>

于 2021-01-28T06:57:59.187 回答