0

我试图计算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/

4

3 回答 3

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
});

小提琴

于 2013-08-29T17:54:02.250 回答
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);
});
于 2013-08-29T17:52:45.753 回答
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();
于 2013-08-29T18:24:17.423 回答