我正在尝试构建一个简单的小费计算器,并希望是否有人知道如何缩短我已经拥有的代码或有任何改进它们的建议。
这是代码:
    $(document).ready(function () {
    // Five Percent
    $('#five').mouseover(function () {
        var yourBill = $('#bill_amount').val();
        var fivePercent = yourBill * 0.05;
        var fiveRounded = fivePercent.toFixed(2)
        $('#you_pay').text('$' + fiveRounded);
    });
    // Ten Percent
    $('#ten').mouseover(function () {
        var yourBill = $('#bill_amount').val();
        var tenPercent = yourBill * 0.10;
        var tenRounded = tenPercent.toFixed(2)
        $('#you_pay').text('$' + tenRounded);
    });
    // Fifteen Percent
    $('#fifteen').mouseover(function () {
        var yourBill = $('#bill_amount').val();
        var fifteenPercent = yourBill * 0.15;
        var fifteenRounded = fifteenPercent.toFixed(2)
        $('#you_pay').text('$' + fifteenRounded);
    });
    // Twenty Percent
    $('#twenty').mouseover(function () {
        var yourBill = $('#bill_amount').val();
        var twentyPercent = yourBill * 0.20;
        var twentyRounded = twentyPercent.toFixed(2)
        $('#you_pay').text('$' + twentyRounded);
    });
    // Twenty Percent
    $('#twenty-five').mouseover(function () {
        var yourBill = $('#bill_amount').val();
        var twentyFivePercent = yourBill * 0.25;
        var twentyFiveRounded = twentyFivePercent.toFixed(2)
        $('#you_pay').text('$' + twentyFiveRounded);
    });
    // Back to $0.00
    $('a').mouseout(function () {
        $('#you_pay').text('$0.00');
    });
    // Starts with $0.00
    $('#you_pay').text('$0.00');
});
你可以在这里看到 jsFiddle:http: //jsfiddle.net/antwonlee/JXpHe/