2

Всем привет. Есть следующая функция:

function changeCount(current, next, selector) {
    $(function () {                     
        $({numberValue: current}).animate({numberValue: next}, { 
            duration: 500, 
            easing: "linear", 
            step: function(val) {  
                $(selector).html(Math.ceil(val)); 
            } 
        });
    }); 
}

Действие очень простое - анимация смены цифр. Вопрос: как ее преобразовать в:

(function( $ ){

  $.fn.changeNumbers = function(next) {

  };

})(jQuery);

Т.е. чтобы в коде к ней можно было обращаться по $(selector).changeNumbers(current, next)

Сделал такое:

(function( $ ){

      $.fn.changeNumbers = function(next) {
          $({numberValue: this.text()}).animate({numberValue: next}, { 
            duration: 500, 
            easing: "linear", 
            step: function(val) {  
                $(this).html(Math.ceil(val)); 
            } 
        });
      };

    })(jQuery);

Но выдает ошибку Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined в строке $(this).html(Math.ceil(val));

Не до конца понимаю контекст this в создании функций, первый раз делаю что-то свое по jquery. Заранее спасибо за помощь!

1 ответ 1

1

В обработчике step this указывает не на исходный элемент, а на сконструированный объект {numberValue: this.text()}

Вам нужно перед запуском animate сохранить this в локальную переменную и в обработчике step обращаться к этой переменной

И еще, в jQuery принято строить цепочки вызовов. Поэтому будет здорово, если Вы вернете переданный this в функцию changeNumbers обратно

(function($) {
  $.fn.changeNumbers = function(next) {
    var obj = this;
    $({numberValue: this.text()}).animate({numberValue: next}, {
      duration: 500,
      easing: "linear",
      step: function(val) {
        obj.html(Math.ceil(val));
      }
    });
    return this;
  };
})(jQuery);

jQuery(function($) {
  $('#btn').click(function() {
    $('#num').text(50).changeNumbers(100).css({"background-color": "yellow"});
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="num">50</div>
<button id="btn">Go</button>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.