jQuery新创建的输入值的总和

时间:2013-08-29 17:50:03

标签: jquery

我试图计算已创建输入值的sum,但不知何故它没有给出正确的结果(例如:如果我创建2输入值为1,则显示3)

HTML:

<a href="#" class="new">new</a>
<a href="#" class="report">report</a>
<div class="container"></div>
<p>total:<span></span></p>

JS:

var total = 0;

$('.new').click(function(){
    $("div").append('<input type="text" name="amount"/>');
});

$('input').live('keyup', function(){
    $('.container input').each(function(){
        total += parseInt($(this).val());
    });
    $('span').html(total);
});

$('.report').live('click', function(){
    $('.container input').each(function(){
        alert('input: '+$(this).val());
    });
});

这是小提琴:http://jsfiddle.net/Wn2cs/4/

3 个答案:

答案 0 :(得分:2)

live()已被弃用,您应该使用on()

问题是全局var total,并且在您继续添加到该全局的每个keyup上,它永远不会重置。它应该在事件处理程序中定义:

$('.container').on('keyup', 'input', function(){
    var total = 0;
    $('.container input').each(function(){
        total += parseInt($(this).val(),10);
    });
    $('span').html(total||0); // avoids NaN
});

FIDDLE

答案 1 :(得分:0)

试试这个:

$('input').live('keyup', function(){
    var total = 0;

    $('.container input').each(function(){
        var value = parseInt($(this).val());
        total += value;
    });
    $('span').html(total);
});

$('.report').live('click', function(){
   alert($('.container input').length);
});

答案 2 :(得分:0)

<div id="input-container">
    <a href="#" class="new">New</a>
    <a href="#" class="report">Report</a>

    <div id="inputs-area"></div>

    <p>Total:<span id="total">0</span></p>
</div>

var InputCalculator = (function ($) {

    /* Static Content */
    var _$container = $('#input-container');
    var _$inputsArea = $('#inputs-area');
    var _$total = $('#total');

    /* Helpers */
    var _getTotal = function () {
        var total = 0;

        _$inputsArea.find('input').each(function () {
            var currentValue = parseInt(this.value, 10);

            if (!isNaN(currentValue)) {
                total += currentValue;
            }
        });

        return total;
    };

    /* Events */
    var _createReportEvent = function (e) {
        e.preventDefault();

        alert('Total: ' + _getTotal());
    };

    var _createInputEvent = function(e) {
        e.preventDefault();

        _$inputsArea.append($('<input>', { type: 'text' }));
    };

    var _recalculateEvent = function() {
        _$total.text(_getTotal());
    };

    var _bindEvents = function () {
        _$container.on('click', 'a.report', _createReportEvent);
        _$container.on('click', 'a.new', _createInputEvent);
        _$inputsArea.on('keyup', 'input', _recalculateEvent);
    };

    var init = function () {
        _bindEvents();
    };

    return {
        init: init
    };

})(jQuery);

InputCalculator.init();