文档就绪时触发更改事件

时间:2013-12-03 17:56:35

标签: javascript jquery

我想重新计算所有内容,不仅是在更改时,还包括页面加载时。

我尝试了以下内容:

$(document).ready(function () {

    //trigger misc costs

        $("input[class~='miscc']").trigger('change');
        $("input[class~='misch']").trigger('change');


//other events here....

    //add up repeater miscaleneous mnumbers
    //dollar amoungs
    $("input[class~='miscc']").change(function (event) {
        //only allow numbers
        this.value = this.value.replace(/[^0-9\.]/g, '');

        var sum = 0;
        var num = 0;
        $("input[class~='miscc']").each(function (event) {
            num = parseFloat($(this).val()) || 0;
            sum = sum + num;
        });
        $("input[id*='txtMiscC']").val(sum.toFixed(2));
        $("input[class~='cost']").trigger('change');
    });

    //hours
    $("input[class~='misch']").change(function (event) {
        //only allow numbers
        this.value = this.value.replace(/[^0-9\.]/g, '');

        var sum = 0.00;
        var num = 0;
        $("input[class~='misch']").each(function (event) {
            num = parseFloat($(this).val()) || 0;
            sum = sum + num;
        });
        $("input[id*='txtMiscH']").val(sum.toFixed(1));
        $("input[class~='hours']").trigger('change');
    });
});

但没有发生任何事情,我做错了吗?

2 个答案:

答案 0 :(得分:3)

在绑定事件处理程序之前触发事件。首先绑定处理程序,然后触发事件。

答案 1 :(得分:0)

将更改事件添加到底部。

$(document).ready(function () {

//other events here....

    //add up repeater miscaleneous mnumbers
    //dollar amoungs
    $("input[class~='miscc']").change(function (event) {
        //only allow numbers
        this.value = this.value.replace(/[^0-9\.]/g, '');

        var sum = 0;
        var num = 0;
        $("input[class~='miscc']").each(function (event) {
            num = parseFloat($(this).val()) || 0;
            sum = sum + num;
        });
        $("input[id*='txtMiscC']").val(sum.toFixed(2));
        $("input[class~='cost']").trigger('change');
    });

    //hours
    $("input[class~='misch']").change(function (event) {
        //only allow numbers
        this.value = this.value.replace(/[^0-9\.]/g, '');

        var sum = 0.00;
        var num = 0;
        $("input[class~='misch']").each(function (event) {
            num = parseFloat($(this).val()) || 0;
            sum = sum + num;
        });
        $("input[id*='txtMiscH']").val(sum.toFixed(1));
        $("input[class~='hours']").trigger('change');
    });

    //trigger misc costs

        $("input[class~='miscc']").trigger('change');
        $("input[class~='misch']").trigger('change');
});