0

我有一个表单,其中有一组可以添加和删除的字段。其中一个字段包含一组数字,这些数字相加以产生总和。你可以在这里看到一个例子:http: //jsfiddle.net/beehive/HGJck/

这是我的问题:当我在表单首次加载时选择不同的数值时,总和不会改变,并且只有一组字段(没有添加)。它仅在我添加或删除字段后才会更改。我怎样才能解决这个问题?

$(document).ready(function() {
/* Add & Remove */
var removeButton = "<button id='remove'>Remove</button>";
$('#add').click(function() {
    $('div.container:last').after($('div.container:first').clone());
    $('div.container:last').append(removeButton);

    /* Sum */
    $(".number").change(function() {
        var combined = -10;
        $(".number").each(function() {
            combined += parseInt(this.value);
        });
        $("#sum").html(combined);
    }).trigger("change"); 

    return false;

});

$('#remove').live('click', function() {
    $(this).closest('div.container').remove();
});

});​
4

1 回答 1

0

我将总和计算移到它自己的函数中,并将组合设置为 0 而不是 -10:jsFiddle 示例

/* Add & Remove */
var removeButton = "<button id='remove'>Remove</button>";
$('#add').click(function() {
    $('div.container:last').after($('div.container:first').clone());
    $('div.container:last').append(removeButton);
    sum();
    return false;
});

$('#remove').live('click', function() {
    $(this).closest('div.container').remove();
    sum();
});

function sum() {
    /* Sum */
    $(".number").change(function() {
        var combined = 0;
        $(".number").each(function() {
            combined += parseInt(this.value);
        });
        $("#sum").html(combined);
    }).trigger("change");
}​
于 2012-07-20T17:15:44.603 回答