jQuery:如何通过单击和更改功能更改输出?

时间:2012-07-20 16:53:09

标签: javascript jquery

我有一个表单,其中有一组可以添加和删除的字段。其中一个字段包含一组数字,这些数字被添加以产生总和。您可以在此处查看此示例: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();
});

});​

1 个答案:

答案 0 :(得分:0)

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

/* 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");
}​