首页 > 解决方案 > 需要帮助制作小费计算器

问题描述

我需要编写一个程序,将一个数字乘以 0.15,这样你就知道你需要留下多少小费。

我试图将我的账单输入放入我的函数中的一个新变量中,因为当我number ()从我的新变量中取出时,我会得到小费总额,但是这样做不会导致任何事情发生,因为 JavaScript 不知道它是一个数字

   <body>
    <input id="bill" placeholder ="How much was you meal?" />

    <button onclick ="tip()"> submit</button>

    <script> let bill = document.querySelector("#bill")

        function tip(){

            let yourTip = number( bill.value * .15)
            let total = yourTip * bill

            console.log ("Your tip  is $" + yourTip)
            console.log ("Your total after the tip is $" + total)
        }
    </script>
   </body>

我不需要仅在控制台中将其打印在屏幕上,并且提示 % 不需要更改。

标签: javascripthtml

解决方案


试试这个:

<style>
  body {
    text-align: center;
  }
</style>

<body>
    <input id="bill" placeholder ="How much was you meal?" />

    <button onclick ="tip()">Calculate</button>
    <h1 id="tip">Tip: $0</h1>
    <h1 id="total">Total: $0</h1>
    <script> let bill = document.querySelector("#bill")

        function tip(){
			let bill = document.getElementById('bill').value;
            let billNum = parseInt(bill);
            let yourTip = billNum * .15;
            let total = yourTip + billNum;

            document.getElementById('tip').innerHTML = "Tip: $" + yourTip;
            document.getElementById('total').innerHTML = "Total: $" + total;
        }
    </script>
   </body>

让我们分解一下:

当您获取输入字段的值时,不指定类型,JavaScript 将值存储为字符串。要将该字符串转换为数字,您需要使用parseInt(x),它告诉浏览器该字符串现在是一个数字,因为您不能将一段文本乘以一个数字。然后,您可以将该数字乘以小费百分比。

此外,您还将小费乘以账单。我添加了一些样式,以及使用innerHTML而不是console.log()显示小费和总账单。


推荐阅读