Javascript变量未正确添加两个变量,仅进行级联 [英] Javascript variables not adding two variables correctly, only concatenating
问题描述
我正在使用html/javascript创建座位预订页面.
I am creating an seat booking page with html/javascript.
这是我正在研究的标准的一部分:
This is part of the criteria I am working on:
-
当1至4位乘客时,每英里车费增加£0.10
When Passengers 1 to 4, Add £0.10 to Fare per mile
当里程数小于或等于10时,则每英里票价为£1.-
When number of miles is less than or equal to 10, then Fare per mile is £1.-
问题是,当我尝试将乘客的总费用+费用相加时,它将变量连接在一起(两种方法都尝试过).
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
任何帮助将不胜感激.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
推荐答案
passengers是字符串,而不是数字.您所做的与说出cost ='Santa'+'Claus'相同;它的成本='1'+'4';不会将"1"和"4"更改为1和4.
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
解决方案是使用 parseInt ,数字或其中之一此答案中的方法.
The solution is to use parseInt, Number, or one of the method from this answer.
这篇关于Javascript变量未正确添加两个变量,仅进行级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!