且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Jquery计算contentEditable文本中的数字总和

更新时间:2022-04-12 22:05:22

看看这个jsFiddle,它可能是你想要:
http://jsfiddle.net/mPvyA/3/

Take a look at this jsFiddle, it might be what you want: http://jsfiddle.net/mPvyA/3/

我稍微修改了一下按钮来添加/删除一个包含的类,然后检查计算结果:

I modified your buttons slightly to add/remove an included class then check for that on calculate:

        $('#exccomp').click(function(){
            $('table').find('.compcost').removeClass('included');
        });

        $('#inccomp').click(function(){
            $('table').find('.compcost').addClass('included');
        });

        $('#calc').click(function(){ 
            var sumArray = [];
            $('table tbody tr').each(function() {
                var $this = $(this), 
                    includedCompCost = $this.find('.compcost').filter('.included').text().match(/\d+/);
                sumArray.push($this.find('.cost').text().match(/\d+/)); 
                if (includedCompCost !== "") { sumArray.push(includedCompCost); }
            });
            var total = 0;
            for (var i = 0; i < sumArray.length; i++) {
                var parsedInt = parseInt(sumArray[i]); 
                if (!isNaN(parsedInt) && parsedInt > 0) { 
                   total += parsedInt; 
                } 
            }
            $('.totalcost').text(total);
        });​