繁体   English   中英

如何在JavaScript / JQuery中修复和重构此计算器脚本

[英]How to fix and refactor this calculator script in JavaScript / JQuery

我决定尝试并了解更多有关JQuery的知识,这就是我的想法。

这项工作应该足够简单,但是我无法解决。 我可以加起来,但是当我更换包裹时,价格一直在上涨。 我知道我也必须添加一些逻辑来减少计数器,但是我认为新鲜的一双眼睛会很棒。

您将如何重构我的代码?

直播: http//www.keithdonegan.com/jquery/calculate/

$(document).ready(function()
{
    var bronze = 50;
    var silver = 100;
    var gold = 200;

    var email_support = 20;
    var email_telephone_support = 50;
    var email_telephone_im_support = 80;

    var total_support = 0;
    var total = 0;

    $('#total span').append(total);

    $('input').click(function()
    {
        var input_id = $(this).attr('id');
        switch(input_id)
        {
        case 'bronze': 
            total = bronze;
            $('#total span').empty().append(total = bronze + total_support);
            break;
        case 'silver':
            total = silver;
            $('#total span').empty().append(total = silver + total_support);
            break;
        case 'gold':
            total = gold;
            $('#total span').empty().append(total = gold + total_support);
            break;
        case 'email-support':
            $('#total span').empty().append(total_support = email_support + total);
            break;
        case 'email-telephone-support':
            $('#total span').empty().append(total_support = email_telephone_support + total);
            break;
        case 'email-telephone-im-support':
            $('#total span').empty().append(total_support = email_telephone_im_support + total);
            break;
        default:
            break;
        }
    });
});

好吧,我不完全确定您对此的计划是什么,但是这里有一些方法可以减少一些缺口:

// inside of $input( 'click' )
// Since you are always calling this function, create a reference to it..
var tot_append = $('#total span').empty().append;

//Later
switch(input_id)
{
    case "bronze":
    case "silver":
    case "gold":
        // The above three have the same functional behavior, an eval
        // would be the perfect way to make it all work on one line
        tot_append( eval( "total = total_support + " + input_id ) );
        break;
    case 'email-support':
    case 'email-telephone-support':
    case 'email-telephone-im-support':
        // See above.
        tot_append( eval( "total_support = total + " + input_id ) );
        break;
}

同样,由于看起来您或多或少地使用变量totaltotal_support作为并行递增器来跟踪相同的值,因此最好改用以下方法:

// This would not need a switch at all.
tot_append( eval( "total += " + input_id ) ); 

暂无
暂无

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

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