1

我发现了一些有用的线程,但没有直接回答我的问题,所以这是具体问题:

为了磨练我有限的 jQuery 技能,我正在创建一个拆分账单/小费计算器,它根据以下输入计算单击按钮时的金额:账单总额、小费百分比、人数。

但是,当我单击按钮时,什么都没有发生。这是jQuery代码:

$(document).ready(function() {
$('button').click(function(){
var Total = $('.Total').val();
var Tip = $('.Tip').val();
var NumberOfPeople = $('.NumberOfPeople').val();
var AdjTotal = (((Tip/100)*Total)+Total).toFixed(2);
var Result = (AdjTotal/NumberOfPeople).toFixed(2);
if(isNaN(AdjTotal)) {
    $('.result').remove();
    $('.error').remove();
    $('.price').append('<p class="error">Please enter valid numbers into the above fields.</p>');
}
else {
    $('.error').remove();
    $('.result').remove();
    $('.price').append('<p class="result">Your total is $' + AdjTotal + ' ' + 'and each person owes: $' + Result + '.</p>');
}
});
});

和 HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css" />
        <script src='script.js'></script>
        <title>Split the Bill</title>
    </head>
    <body>
        <div class="header">
            <h1>Split the Bill</h1>
        </div>
        <div>
            <table>
                <tbody>
                    <tr>
                        <td align="right">
                            Bill Total: $
                        </td>
                        <td text-align="left">
                            <input class="Total" type="text" name="Total">
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Tip Percentage: 
                        </td>
                        <td text-align="left">
                        <input class="Tip" type="text" name="Tip"> %
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Number of People: 
                        </td>
                        <td colspan=3>
                            <input class="NumberOfPeople" type="text" name="Number of People">
                        </td>
                    </tr>
                    <tr>
                        <td colspan=4 align="right">
                            <button>Calculate</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="price">
        </div>
    </body>
</html> 

谢谢你的帮助!

4

1 回答 1

1

问题是这一行:

var AdjTotal = (((Tip/100)*Total)+Total).toFixed(2);

总计是一个字符串。你需要强制它是一个数字:

var AdjTotal = (((Tip/100)*Total)+Total/1).toFixed(2);

http://jsfiddle.net/59WXX/

于 2013-03-18T15:34:25.580 回答