遇到实时计算问题,计算每个击键

时间:2013-04-09 19:19:06

标签: javascript jquery html

我有一个表根据用户输入的输入计算总数。我的问题是jquery代码计算每个键击,而不是一旦你停止键入“抓住”整个数字。代码如下,任何帮助都将不胜感激。

$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);

});

//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
    var tierSelected = $(this).attr('data-year');
    var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());

    $('.alertbox_error_' + tierSelected).hide();
    if (isNaN(numberSeats) || numberSeats == 0) {
        $('.alertbox_error_' + tierSelected).show();
    } else {
        $('.alertbox_error_' + tierSelected).hide();

        var seatHigh = 0;
        var seatLow = 0;
        var seatBase = 0;
        var yearTotal = 0;
        var totalsArray = [];
        var currentYear = 0;

        $('.tier_' + tierSelected).each(function() {
            seatLow = $(this).attr('data-seat_low');
            firstSeatLow = $(this).attr('data-first_seat_low');
            seatHigh = $(this).attr('data-seat_high');
            seatBase = $(this).attr('data-base_cost');
            costPerSeat = $(this).attr('data-cost_per_seat');
            years = $(this).attr('data-year');
            seats = 0;

            if (years != currentYear) {
                if (currentYear > 0) {
                    totalsArray[currentYear] = yearTotal;
                }
                currentYear = years;
                yearTotal = 0;
            }

            if (numberSeats >= seatHigh) {
                seats = Math.floor(seatHigh - seatLow + 1);
            } else if (numberSeats >= seatLow) {
                seats = Math.floor(numberSeats - seatLow + 1);
            }

            if (seats < 0) {
                seats = 0;
            }
            yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
        });

        totalsArray[currentYear] = yearTotal;

        totalsArray.forEach(function(item, key) {
            if (item > 1000000) {
                $('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
            } else {
                $('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

你需要一个setTimeout,以及一种在按键上杀死/重置它的方法。

我个人会这样做:

var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});

function runEstimateTotal(){
    clearTimeout(calc_delay);
    calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}

function EstimateTotal() {
    ....

这样做会促使系统在每次按键后计算100ms - 除非检测到另一个事件(即调用runEstimateTotal),在这种情况下延迟倒计时重置。