Доступ к функции плагина Jquery извне - PullRequest
0 голосов
/ 08 февраля 2012

Я новичок в jquery, с некоторым базовым пониманием.

Я пытаюсь использовать jOdometer.js https://github.com/jesucarr/jodometer.Я могу получить одометр хорошо, и метод setInterval по умолчанию делает тик одометра.

Есть раздел кода

function advanceCounter() {
            setNumbers(counter);
            counter = counter + settings.increment; // increment the number 
            // if we reach the end clear the interval and use the ending number
            if(settings.counterEnd != false && counter >= settings.counterEnd){
                clearInterval(counterInterval);
                setNumbers(settings.counterEnd);
            }
        }
        // to move the colums from one number position to another
        function setNumbers(counter){
            digits = String(counter).split('.'); // check decimals
            // if we where using decimals
            if (decimalsArray.length > 0){
                // for each decimal digit, update the old digit position to the new
                for (i=0;i<decimalsArray.length;i++){
                    oldDigit = decimalsArray[i];
                    // the new numer could have not decimal part, but we need it anyway
                    if (digits[1]){
                        decimalsArray[i] = digits[1].charAt(i);
                    }
                    if (decimalsArray[i] == ''){
                        decimalsArray[i] = '0';
                    }
                    updatePosition($('.jodometer_decimal_'+i, scope), parseInt(decimalsArray[i]), parseInt(oldDigit));
                }
            }

            integers = digits[0];
            j=integers.length-1;
            // for each integer digit, update the old digit position to the new
            for (i=0;i<integersArray.length;i++){
                oldDigit = integersArray[i];
                integersArray[i] = integers.charAt(j);
                if (integersArray[i] == ''){
                    integersArray[i] = '0';
                }
                //alert($(this));
                updatePosition($('.jodometer_integer_'+i, scope), parseInt(integersArray[i]), parseInt(oldDigit));
                j--;
            }
        }
        // changes the column position from one number to another
        function updatePosition(col, newDigit, oldDigit){
            if(newDigit != oldDigit){
                col.stop();
                // if the number is 0 use the bottom 0 in the image, and change intantly to the top 0
                if (newDigit == 0){
                    col.animate({top: (10*settings.heightNumber*-1)+zeroSet}, settings.speed, settings.easing).animate({top: zeroSet},1, 'linear');
                }else{
                    // if the new number is lower than the old, we have to go to the bottom 0 and start from the top 0, with the apropiate speed, to don't note the jump
                    if (newDigit < oldDigit){
                        col.animate({top: (10*settings.heightNumber*-1)+zeroSet}, settings.speed*((10-oldDigit)/10), 'linear').animate({top: zeroSet},1, 'linear').animate({top: (newDigit*settings.heightNumber*-1)+zeroSet}, settings.speed*oldDigit/10, settings.easing);
                    }else{
                        col.animate({top: (newDigit*settings.heightNumber*-1)+zeroSet}, settings.speed, settings.easing);
                    }
                }
            }
        }

, который обновляет одометр.Я использую ajax для получения новых данных и хочу обновить показания одометра.Как я могу позвонить advanceCounter() или setNumbers() с моей веб-страницы, чтобы обновить одометр?

Справка.

Вот демонстрация самого плагина (от самого автора).http://www.frontendmatters.com/demos/jodometer/

Ответы [ 2 ]

1 голос
/ 08 февраля 2012

Похоже, вы можете просто установить его, когда получите новые данные, например:

function updateTimer(newVal)
{
    $(".myCounter").jOdometer({ counterStart: newVal, counterEnd:newVal, numbersImage: 'images/jodometer-numbers.png'});
}

Я не уверен, что вы хотите, чтобы приращение было, если оно есть, но этодолжен сделать трюк.

Обновление:

Вот оно со встроенной анимацией.

Откройте файл jquery.jodometer.js.Посмотрите на строку 100 (прямо под функцией 'advanceCounter ()') и добавьте следующее:

$.fn.Advance = function(newVal)
{
    setNumbers(newVal);
}

Теперь вы можете увеличить счетчик, выполнив:

$("#MyCounterDiv").Advance(150); //150  whatever new value you want.

Обновить2:

Я тестировал только с одним счетчиком.aVC указал, что будет затронут только последний инициализированный счетчик.Вот как я работал с этим:

Замените функцию setNumbers на эту:

function setNumbers(counter, elem){
    digits = String(counter).split('.'); // check decimals
    // if we where using decimals
    if (decimalsArray.length > 0){
        // for each decimal digit, update the old digit position to the new
        for (i=0;i<decimalsArray.length;i++){
            oldDigit = decimalsArray[i];
            // the new numer could have not decimal part, but we need it anyway
            if (digits[1]){
                decimalsArray[i] = digits[1].charAt(i);
            }
            if (decimalsArray[i] == ''){
                decimalsArray[i] = '0';
            }
            var theScope = (elem) ? elem : scope;
            console.log(theScope);
            updatePosition($('.jodometer_decimal_'+i, theScope), parseInt(decimalsArray[i]), parseInt(oldDigit));
        }
    }

    integers = digits[0];
    j=integers.length-1;
    // for each integer digit, update the old digit position to the new
    for (i=0;i<integersArray.length;i++){
        oldDigit = integersArray[i];
        integersArray[i] = integers.charAt(j);
        if (integersArray[i] == ''){
            integersArray[i] = '0';
        }
        var theScope = (elem) ? elem : scope;
        console.log(theScope);
        updatePosition($('.jodometer_integer_'+i, theScope), parseInt(integersArray[i]), parseInt(oldDigit));
        j--;
    }
}

Я добавил еще один параметр "elem", который будет передан в Advance функция, которую мы добавили ранее.Просто нужно изменить функцию $. Fn.Advance следующим образом:

$.fn.Advance = function(newVal)
{
    setNumbers(newVal, $(this));
}

Наконец, я обнаружил, что по какой-то причине мне нужно было удалить оператор if из updatePosition функция.Это утверждение if выясняет, пытаетесь ли вы сказать ему «изменить» на тот же номер.Он ломается, потому что проверяет неправильные настройки счетчика.Мы могли бы обойти это, если это важно, но я просто решил это закомментировать: P

function updatePosition(col, newDigit, oldDigit){
    //if(newDigit != oldDigit){
        col.stop();
        // if the number is 0 use the bottom 0 in the image, and change intantly to the top 0
        if (newDigit == 0){
            col.animate({top: (10*settings.heightNumber*-1)+zeroSet}, settings.speed, settings.easing).animate({top: zeroSet},1, 'linear');
        }else{
            // if the new number is lower than the old, we have to go to the bottom 0 and start from the top 0, with the apropiate speed, to don't note the jump
            if (newDigit < oldDigit){
                col.animate({top: (10*settings.heightNumber*-1)+zeroSet}, settings.speed*((10-oldDigit)/10), 'linear').animate({top: zeroSet},1, 'linear').animate({top: (newDigit*settings.heightNumber*-1)+zeroSet}, settings.speed*oldDigit/10, settings.easing);
            }else{
                col.animate({top: (newDigit*settings.heightNumber*-1)+zeroSet}, settings.speed, settings.easing);
            }
        }
    //}
}
0 голосов
/ 08 февраля 2012

Удалите старый счетчик и замените его новым элементом, для которого вы можете вызвать плагин jodometer:

$.ajax({
    success : function (serverResponse) {

        //create a new element to add to the DOM
        var $counter = $('<div id="counter" />');

        //replace the old `#counter` element with the new one (which has nothing bound to it)
        $('#counter').replaceWith($counter);

        //now initialize the plugin on the new DOM element
        $counter.jodometer({ ... });
    }
});

Обновление

Чтобы оживить изменение контента, вы можете сделать что-то вроде этого:

$.ajax({
    success : function (serverResponse) {

        //create a new element to add to the DOM
        var $counter = $('<div id="counter" style="display:none;" />');

        //replace the old `#counter` element with the new one (which has nothing bound to it)
        $('#counter').fadeOut(500).replaceWith($counter);

        //now initialize the plugin on the new DOM element
        $counter.fadeIn(500).jodometer({ ... });
    }
});

Обратите внимание, что я добавил style="display:none;" к новому элементу перед добавлением его в DOM, таким образом вы можете fadeIn() элемент.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...