javascript - 将 jQuery 插件转换为函数并移动到现有 JavaScript 对象中

标签 javascript jquery

下面是一个 JavaScript 项目的基本结构,下面是一个小型 jQuery 插件库。

我的目标是基本上将底部 jQuery 插件集成到我下面的 JavaScript 项目中。

在下面的项目代码中,jQuery 插件在 get_social_counts 函数内调用。如果 jQuery 插件可以转换为常规函数并放入项目中,则可以更新 get_social_counts 内部对其的调用,以简单地从同一对象调用函数。

尽管有任何帮助,但我不确定如何将 jQuery 插件集成到我的代码中。

JS 库

var SocialShareButtons = {

  init: function() {
    this.getPageDataToShare();
    this.build_social_btn_html();
    this.buildShareWindow();
  },

  get_social_counts: function(thisUrl) {

            $('.sharedCount .count').countTo({
                from: 0,
                to: totalCount,
                speed: 1000,
                refreshInterval: 5,
                formatter: function (value, options) {
                    return value.toFixed(options.decimals);
                },
            });

  },

  ////////////// several other functions.......

}

jQuery 插件

  $.fn.countTo = function (options) {
    options = options || {};

    return $(this).each(function () {
      // set options for current element
      var settings = $.extend({}, $.fn.countTo.defaults, {
        from:            $(this).data('from'),
        to:              $(this).data('to'),
        speed:           $(this).data('speed'),
        refreshInterval: $(this).data('refresh-interval'),
        decimals:        $(this).data('decimals')
      }, options);

      // how many times to update the value, and how much to increment the value on each update
      var loops = Math.ceil(settings.speed / settings.refreshInterval),
        increment = (settings.to - settings.from) / loops;

      // references & variables that will change with each update
      var self = this,
        $self = $(this),
        loopCount = 0,
        value = settings.from,
        data = $self.data('countTo') || {};

      $self.data('countTo', data);

      // if an existing interval can be found, clear it first
      if (data.interval) {
        clearInterval(data.interval);
      }
      data.interval = setInterval(updateTimer, settings.refreshInterval);

      // initialize the element with the starting value
      render(value);

      function updateTimer() {
        value += increment;
        loopCount++;

        render(value);

        if (typeof(settings.onUpdate) == 'function') {
          settings.onUpdate.call(self, value);
        }

        if (loopCount >= loops) {
          // remove the interval
          $self.removeData('countTo');
          clearInterval(data.interval);
          value = settings.to;

          if (typeof(settings.onComplete) == 'function') {
            settings.onComplete.call(self, value);
          }
        }
      }

      function render(value) {
        var formattedValue = settings.formatter.call(self, value, settings);
        $self.text(formattedValue);
      }
    });
  };

  $.fn.countTo.defaults = {
    from: 0,               // the number the element should start at
    to: 0,                 // the number the element should end at
    speed: 1000,           // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,           // the number of decimal places to show
    formatter: formatter,  // handler for formatting the value before rendering
    onUpdate: null,        // callback method for every time the element is updated
    onComplete: null       // callback method for when the element finishes updating
  };

  function formatter(value, settings) {
    return value.toFixed(settings.decimals);
  }
}(jQuery));

最佳答案

注意到它只是更新 DOM 的计数器,我认为你可以重新编写逻辑。

作为一个 jquery 插件,这将应用于每个选定的 dom 元素。使用以下内容,您需要在此处使用循环或针对多个元素修改函数本身。

希望以下内容有所帮助... JS 函数:

function countTo(dom, to, from, speed, refreshInterval, todecimals) {

    var loops = Math.ceil(speed / refreshInterval),
        increment = (to - from) / loops,
        loopCount = 0,
        value = from,
        timer;

    if (timer) clearInterval(timer);
    timer = setInterval(updateTimer, refreshInterval);

    render(value);

    function updateTimer() {
        value += increment;
        loopCount++;
        render(value);

        if (loopCount >= loops) {
            clearInterval(timer);
            value = to;
        }
    }

    function render(value) {
        dom.textContent = value.toFixed(todecimals);
    }
}

你可以这样调用它:

var domElement = $('.sharedCount .count')[0];

countTo(domElement, 0, totalCount, 1000, 5, options.decimals);

关于javascript - 将 jQuery 插件转换为函数并移动到现有 JavaScript 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34563036/

相关文章:

javascript - 无法在按钮提交处理程序中使用变量

javascript - 带逗号的 jQuery 模板格式

javascript - 如果 else 语句检查并查看某个 img 标签是否附加到 div 将不会执行

php - 如何使用文档准备选择selectpicker的默认值?

javascript - 如何仅启用一列值

javascript - Usemin 和多个构建配置

javascript - 如何避免使用 Bootstrap 折叠一次打开多个元素

javascript - 使用 jquery 添加两个变量

javascript - 使用ajax将php数组传递给javascript

javascript - 你能把 'compile' html文件放在一起来模拟 'include'函数吗?