[英]Need help making a tip calculator
我需要編寫一個程序,該程序將接受一個數字並將其乘以.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()
來顯示提示和總賬單。
嘗試這個
<input id="bill" type="number" placeholder="How much was you meal?" />
<button onclick="tip()">submit</button>
<script>
function tip() {
var bill = parseInt(document.getElementById("bill").value);
console.log(bill);
let yourTip = bill * 0.15;
let total = yourTip + bill;
console.log("Your tip is $" + yourTip);
console.log("Your total after the tip is $" + total);
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.