【发布时间】:2016-05-14 03:00:13
【问题描述】:
我有一个不知道如何解释的案例: 让我烦恼的是,我打开代码,写了一些值(例如: 你付了多少钱:100 你的服务怎么样:10 有多少人共享:2)在我点击计算之前,我打开控制台。如果我写:
>bill.value
<"100"
正如预期的那样,我得到了一个字符串。但是然后我点击计算,我得到的是:
100
5
为什么是 100?为什么它突然返回数字 insted 的字符串?
最后我该如何用它做数学运算。我唯一要变成数字的是数字(bill.value)。服务和人还应该是字符串?
var button = document.querySelector("button");
var tip = document.getElementById("tip");
var total;
button.addEventListener("click", function() {
var bill = document.querySelector("input");
console.log(bill.value)
var people = document.getElementById("people").value;
var service = document.getElementsByTagName("select")[0].value;
total = (service * Number(bill.value)) / people
tip.textContent = total;
console.log(total)
});
<h1>Tip Calculator</h1>
<div>How much was your bill?</div>
<label for="bill">$</label>
<input type="number" id="bill">
<div>How was your service?</div>
<select>
<option disabled selected value="0">Choose</option>
<option value="0.30">30% - Outstanding</option>
<option value="0.20">20% - Good</option>
<option value="0.15">15% - It was okaya</option>
<option value="0.10">10% - Bad</option>
<option value="0.05">5% - Terible</option>
</select>
<div>How many people are sharing the bill?</div>
<label>
<input type="number" id="people">people</label>
<button>Calculate!</button>
<span id="tip"></span>
【问题讨论】:
标签: javascript string dynamic-typing