我需要编写一个程序,该程序将接受一个数字并将其乘以.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>
我不需要仅在控制台中将其打印在屏幕上,并且提示%也不需要更改。
答案 0 :(得分:0)
尝试一下:
<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()
来显示小费和总账单。
答案 1 :(得分:-1)
尝试
<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>