简体   繁体   English

jQuery:如何使用点击和更改功能更改输出?

[英]jQuery: how to change output with click and change functions?

I have a form where I have a group of fields that can be added and removed. 我有一个表格,其中有一组可以添加和删除的字段。 One of these fields contains a set of numbers that are added to produce a sum. 这些字段之一包含一组数字,这些数字相加即可产生总和。 You can see an example of this here: http://jsfiddle.net/beehive/HGJck/ :你可以在这里看到这样一个例子http://jsfiddle.net/beehive/HGJck/

Here's my problem: the sum does not change when I select a different number value when the form first loads, and there is only one group of fields (nothing added). 这是我的问题:表单第一次加载时,当我选择一个不同的数值时,总和不变,并且只有一组字段(未添加任何内容)。 It only changes after I've added or removed fields. 只有在我添加或删除字段后,它才会更改。 How can I fix this? 我怎样才能解决这个问题?

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

});​

I moved the sum calculation into its own function and set combined to 0 instead of -10: jsFiddle example 我将求和计算移到其自己的函数中,并将组合设置为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");
}​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM