javascript - 如何为这个 jquery 增量插件编写一个函数?

标签 javascript jquery

我找到了一个不错的 jquery 增量脚本。增量部分可以接受一个函数或只是一个常规数字。我希望以 1 到 100 之间的随机数增加。我将如何为此编写函数?

$( document ).ready( function()
{
  $( '.tick' ).ticker(
  {
    incremental : 1,
    delay       : 1500,
    separators  : true
  });
   $(".comma-change").html(".");  
});

<span class="tick">2,354,456</span>

因此,我不想在增量字段中增加 1,而是编写一个用随机数更新的函数。在其他帖子的帮助下,我可以毫无问题地编写创建随机数的函数:

function random_generator (min, max) {
    return Math.random() * (max - min) + min;
}

但我无法直接将其用于此。

这是插件的增量部分:

  Tick = (function() {

    function Tick(element, options) {
      this.element = element;
      if (options == null) options = {};
      this.running = false;
      this.options = {
        delay: options.delay || 1000,
        separators: options.separators != null ? options.separators : false,
        autostart: options.autostart != null ? options.autostart : true
      };
      this.increment = this.build_increment_callback(options.incremental);
      this.value = Number(this.element.html().replace(/[^\d.]/g, ''));
      this.separators = this.element.html().trim().split(/[\d]/i);
      this.element.addClass('tick-active');
      if (this.options.autostart) this.start();
    }

    Tick.prototype.build_increment_callback = function(option) {
      if ((option != null) && {}.toString.call(option) === '[object Function]') {
        return option;
      } else if (typeof option === 'number') {
        return function(val) {
          return val + option;
        };
      } else {
        return function(val) {
          return val + 1;
        };
      }
    };

然后这一点:

Tick.prototype.tick = function() {
  this.value = this.increment(this.value);
  this.render();
  return this.set_timer();
};

最佳答案

您可能需要更新增量脚本的源代码。但是,如果幸运的话,您也许可以使用一些技巧来避免这种情况。

增量脚本中可能有这样的东西:

function(options) {
    //...
    currentValue += options.incremental;
    //...
}

如果是这种情况,您可以在事后定期调整 options.incremental 的值,如下所示:

var opts;
$( '.tick' ).ticker(opts = {
    incremental : 1,
    delay       : 1500,
    separators  : true
});

setInterval(function () { 
    var min = 1, max = 100; //adjust min/max to suit your needs.
    opts.incremental = Math.random() * (max - min) + min;
}, 500); //any number under 1500 is probably fine

这有点 hack,但它可能会起作用。可能比更新插件代码更容易。如果它不起作用,您可能必须直接增强插件。

关于javascript - 如何为这个 jquery 增量插件编写一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12482202/

相关文章:

javascript - 模态弹出错误: "The parameters dictionary contains a null entry for parameter ' id' of non-nullable type

javascript - OnClick 函数出错

javascript - 使用 jQuery 的自动可点击图片库,第一张图片淡入/淡出但其他图片不淡入?

javascript - Jquery Ajax 调用返回

javascript - 为什么 node.js html5 Canvas 演示不能在本地运行?

jquery - CSS transition 和 jQuery fade 之间的冲突

javascript - Google 网站优化器控件 Javascript

javascript - 将多个 jQuery 元素选择器传递给一个函数

jquery - 像菜单一样的 CSS 分步向导

ruby-on-rails - Ajax 提交表单 ruby​​ on Rails