javascript - 需要帮助制作小费计算器
问题描述
我需要编写一个程序,将一个数字乘以 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>
我不需要仅在控制台中将其打印在屏幕上,并且提示 % 不需要更改。
解决方案
试试这个:
<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()
显示小费和总账单。
推荐阅读
- azure - 如何使用 java 生成 azure blob 存储 SAS url?
- javascript - 如何在javascript中使用地图?
- gradle - Gradle警告无法分配'LinkedHashMap
' 到 ' 类 '关于想法 - java - 如何使用像 tika 这样的 java 开源 api 从 docx 文件中获取嵌入的图片?
- linux - bash 如何使用 CTRL+C 杀死子进程
- react-native - 无法运行 react-native run-android?
- mysql - 将公斤和克单位乘以每公斤的价格
- ruby-on-rails - 重构允许更改输入的参数
- php - 如何使自定义购物车费用在 WooCommerce 中征税
- javascript - Next js中页面刷新时查询值丢失?[给出的例子]