javascript - 给div添加单独用JS递增的文本

标签 javascript jquery html function

我正在尝试做与此网站上相同的事情http://www.internetlivestats.com/one-second/

正如您所看到的,有一个数字每秒增加 x 次。

我被困住了,如果有人能帮助我那就太好了。 这是我到目前为止所想出的(我知道它现在不起作用)

index.html

<div class="twitter"></div>
<div class="instagram"></div>

脚本.js

var total = 0;
var twitterMultiplier = 7135;
var instagramMultiplier = 487;

var update = function() {
  document.getElementByClassName("twitter").innerHTML = "Tweets per second: " + Math.round(total + 7135);
  document.getElementByClassName("instagram").innerHTML = "Images per second: " + Math.round(total + 487);
}
window.setInterval(function(){
  update();
}, 100);

最佳答案

您没有对局部变量执行任何突变,因此您看到的值始终是 7135 和 487。您还存在一些语法错误。

以下是我可能采取的稍微不同的处理方式。

    // Maintain and simple map of the settings you need
    var timeMap = {
      'twitter': {
        total: 0,
        rate: 7135,
        label: 'Tweets per second: '
      },
      'instagram': {
        total: 0,
        rate: 487,
        label: 'Images per second: '
      }
    };

    // The update function loops over the map, updates each total by
    // the rate value, and uses the map key and label to find the element 
    // by ID in the DOM and builds the output string
    var update = function() {
      for (var site in timeMap) {
        timeMap[site].total += timeMap[site].rate;
        document.getElementById(site).innerHTML = timeMap[site].label + timeMap[site].total.toString();
      }
    };

    // runs every 1000 milliseconds
    window.setInterval(update, 1000);
<div id="twitter"></div>
<div id="instagram"></div>

这种方法可以让您轻松添加越来越多的网站 - 无需更改 update() 函数。

关于javascript - 给div添加单独用JS递增的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35855933/

相关文章:

html - knockout js 如何在下拉选定索引更改时触发事件

javascript - JQuery,找出可见的内容并将其隐藏

javascript - 将样式表链接到 ID

javascript - 如何让画线在 Internet Explorer 中工作?

jQuery .on() 委托(delegate) mouseenter 和 mouseleave

javascript - jQuery DataTable 显示条目、搜索框和排序不起作用?

html - CSS3 : Use On-hover Event to Set Semi-transparent Overlay on an Image

javascript - 缩小屏幕时保持图像位置

javascript - 复杂对象的 Angular 自定义过滤器

javascript - 如何在javascript中将大的负科学记数法数字转换为十进制记数法字符串?