关于简化我的代码的任何想法?

时间:2015-04-27 19:31:57

标签: javascript jquery dry

如何在这里申请干练习?我知道我重复了很多,我不喜欢它。但我不知道如何解决它。简化这个单位转换器会很棒。感谢大家的帮助。

$(':input').bind('keypress keydown keyup change',function(){
        var input = parseFloat($(':input[name="input"]').val())

        var output1  = '';
        var output2  = '';

        if ($("#unitSelector").val() === 'celsius'){
            output1 = ((input * 9) / 5 + 32).toFixed(5).toString();
            output2 = (input + 273.15).toFixed(5).toString();

        $(':input[name="output1"]').val(output1 + " " + "Fahrenheit");
        $(':input[name="output2"]').val(output2 + " " + "Kelvin");
        }

        if ($("#unitSelector").val() === 'fahrenheit') {
            output1 = ((input - 32) * 5 / 9).toFixed(5).toString();
            output2 = ((input + 459.67) * 5 / 9).toFixed(5).toString();

        $(':input[name="output1"]').val(output1 + " " + "Celsius");
        $(':input[name="output2"]').val(output2 + " " + "Kelvin");
        }

        if ($("#unitSelector").val() === 'kelvin') {
            output1 = (input - 273.15).toFixed(5).toString();
            output2 = (9 / 5 * (input - 273) + 32).toFixed(5).toString();

        $(':input[name="output1"]').val(output1 + " " + "Celsius");
        $(':input[name="output2"]').val(output2 + " " + "Fahrenheit");
        }
    });

1 个答案:

答案 0 :(得分:1)

这是一个刺:

$(':input').bind('keypress keydown keyup change', function () {

    var input = parseFloat($(':input[name="input"]').val()),
        type = $("#unitSelector").val(),
        output1 = '',
        output2 = '',
        tag1 = 'Celsius',
        tag2 = 'Kelvin';

    switch (type) {
        case 'celsius':
            output1 = ((input * 9) / 5 + 32);
            output2 = (input + 273.15);
            tag1 = 'Fahrenheit';
            break;
        case 'fahrenheit':
            output1 = ((input - 32) * 5 / 9);
            output2 = ((input + 459.67) * 5 / 9);
            break;
        case 'kelvin':
            output1 = (input - 273.15);
            output2 = (9 / 5 * (input - 273) + 32);
            tag2 = 'Fahrenheit';
            break;
    }

    $(':input[name="output1"]').val(output1.toFixed(5).toString() + " " + tag1);
    $(':input[name="output2"]').val(output2.toFixed(5).toString() + " " + tag2);

});