Почему счетчик номеров jQuery не обновляется при изменении атрибута html? - PullRequest
0 голосов
/ 25 сентября 2019

Я использую JQuery Number Counter , чтобы оживить некоторые цифры на моем сайте.Когда страница загружена, JQuery Number Counter работает нормально.Я получаю номера, используя вызов Ajax к моей базе данных.Я устанавливаю атрибут данных «data-to» динамически на основе возвращенного значения из вызова Ajax.Однако, если я инициирую вызов Ajax во второй раз с измененным значением атрибута данных, счетчик чисел будет работать с начальным значением data-to вместо нового обновленного значения.Я не могу понять, почему счетчик чисел не использует новое значение, восстановленное вызовом Ajax.Вот мой код для инициации счетчика чисел:

$(document).ready(function(){
    getSearchCount();

    $('#tags').on('itemAdded', function(event) {
        getSearchCount();
    });

    $('#tags').on('itemRemoved', function(event) {
        getSearchCount();
    });
});

В журнале консоли я проверил, что значение переменной 'projectCounter' в приведенном ниже коде фактически меняется для каждого вызова Ajax.Переменная используется для установки значения атрибута данных «data-to».

Вот код для вызова Ajax:

function getSearchCount()
{ 
    var sok = document.querySelector('[name="searchstring"]').value;

    $.ajax({
        url: '../../core/search/get_general_count.php', 
        data:{sok:sok}, 
        dataType: 'json', 
        success: function(response)
        {
            console.log(JSON.stringify(response));
            var searchCount = response;

            for (var i in searchCount)
            {
                var countrow = searchCount[i];
                projectCount = countrow[0];
                //var profileid = profilerow[0];
                //var profiletype = profilerow[2];
            }

            $('#count-projects').attr('data-to',projectCount);
            console.log(projectCount);

            (function ($) {
                $.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.html(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));

jQuery(function ($) {
// custom formatting example
$('.count-number').data('countToOptions', {
    formatter: function (value, options) {
        return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+ 
 (?!\d))/g, ' ');
    }
});

// start all the timers
$('.timer').each(count);  

function count(options) {
    var $this = $(this);
    options = $.extend({}, options || {}, $this.data('countToOptions') || 
{});
    $this.countTo(options);
}
});

    //alert(detrow.toString());     
  }, // end response success
error: function (jqXHR, exception) {
    var msg = '';
    if (jqXHR.status === 0) {
        //msg = 'Not connect.\n Verify Network.';
    } else if (jqXHR.status == 404) {
        msg = 'Requested page not found. [404]';
    } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
    } else if (exception === 'parsererror') {
        msg = 'Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        msg = 'Time out error.';
    } else if (exception === 'abort') {
        msg = 'Ajax request aborted.';
    } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }
        alert(msg);
    }
    }); //end ajax
  }; // end function

1 Ответ

0 голосов
/ 25 сентября 2019

Я понял это.Я переместил счетчик чисел jQuery из моей функции Ajax и вместо этого вызвал счетчик чисел jQuery из моей функции Ajax.HTML:

<h5 id="count-projects" class="description-header timer count-title count-number" 
 style="font-size: 40px;color: #808080;" data-to="" data-speed="500"></h5>

jQuery:

 $('.timer').countTo({from: 0, to: projectCount});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...