繁体   English   中英

JavaScript-删除也会重新计算总数的表格行

[英]Javascript - delete table row that also recalculates totals

我有一个表格,允许用户进行一些选择并输入一些数字,然后这些数字将用于自动计算总数。 我最近添加了一些功能,可以向表中添加其他行,并且还允许用户根据需要删除行。

我还需要“删除”按钮来同时强制重新计算总数,而目前它只是删除该行并保留原来不正确的原始总数。

这是我删除表行的脚本:

$(window).load(function(){
//Sum Table Cell and Map

 $('#lastYear')
    .on('change', 'select', calc)
    .on('keyup', 'input', calc);

function calc(){

    $('#lastYear tr:has(.risk)').each(function(i,v){

        var $cel = $(v.cells);

        var $risk = $cel.eq(1).find('option:selected').val();
        var $numb = $cel.eq(2).find('input').val();
        var $weeks = $cel.eq(3).find('input').val();
        var $avg = ($numb * $weeks) / 52;
        var $avgRounded = Math.round( $avg * 10 ) / 10;

        $cel.eq(4).find('input').val($avgRounded);

    });   

    var tot = {high:0,moderate:0}; 

    $('#lastYear tr:has(.risk) option:selected')
                .map(function(i){
                    var el = $(this).val();
                    var qty = parseFloat(
$('#lastYear tr:has(.risk)').eq(i).find('td:last')
    .prev().prev() // call prev method twice
    .find('input').val()
);

                    if (!tot.hasOwnProperty(el)) {
                        tot[el] = 0;            
                    }
                    tot[el] += qty
                    return tot;
                }).get();

    // console.log(tot);
     $('#textfield4').val(tot.moderate.toFixed(1));
    $('#textfield5').val(tot.high.toFixed(1));

    }
});//]]>  

这是进行计算的脚本:

$('#lastYear').on('click', '.delbtn', function () {
    $(this).closest('tr').remove()
});

var newIDSuffix = 2;
$('#lastYear').on('click', '.addbtn', function () {
    var thisRow = $(this).closest('tr')[0];
    $(thisRow).find('.delbtn').show();

    var cloned = $(thisRow).clone();
    cloned.find('input, select').each(function () {
        var id = $(this).attr('id');
        id = id.substring(0, id.length - 1) + newIDSuffix;
        $(this).attr('id', id);
    });

    cloned.insertAfter(thisRow).find('input:text').val('');
    cloned.find('.delbtn').hide();
    cloned.find("[id^=lastYearSelect]")
    .autocomplete({
        source: availableTags,
        select: function (e, ui) {

            $(e.target).val(ui.item.value);
            setDropDown.call($(e.target));
        }
    }).change(setDropDown);

    $(this).remove();
    newIDSuffix++;
});

我已经设置了一个工作的jsFiddle ,这可能有助于解释发生了什么。

我是Java语言的新手,但对我来说,我似乎需要以某种方式将delete函数与calculate函数结合起来?

尝试这个

$('#lastYear').on('click', '.delbtn', function () {
    $(this).closest('tr').remove();
    calc();
});

您只需要在.delbtn点击处理程序中调用calc() calc函数和delete按钮单击处理程序目前处于不同的上下文中……但是,如果它们在相同的作用域内(将它们移动到相同的文件和相同的onload块中),就可以了。

我已经更新了您的JSFiddle,以演示http://jsfiddle.net/6KPxq/2/

暂无
暂无

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

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