0
我正在做一個java腳本應用程序,用於計算每加侖使用的Miles驅動/加侖和使用的加侖*價格。我有兩個問題:如何在Java腳本中寫入頁面DOm模型
1)當我輸入所有的價格每加侖自動添加另一個零。例如40,變成400. 2)我正在寫這兩個計算結果在按鈕下面。 如果任何人都可以給我指導或幫助,我會很感激。
<!DOCTYPE
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
}
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function() {
var miles = parseFloat($("miles").value); //alert(miles);
var gallons = parseFloat($("gallons").value);
var costGallon = document.getElementById("costGallon").value;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
}
else {
var mpg = miles/gallons;
var costGallon = gallons*costGallon;
$("costGallon").value=costGallon.toFixed(2);
//alert("your total is" +mpg);
alert("your total new is " + costGallon);
//cost of trip = gallons used * price per gallon
}
}
//write to the page
window.onload = function() {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
}
</script>
</head>
<section>
<body>
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br><br>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br><br>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br><br>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span>
</section>
</body>
</html>
這裏是你的代碼修改 – mareklspak 2015-03-03 01:46:45
你好,所以當我輸入10所使用的氣體加侖,然後40每加侖的價格,然後我按計算MPG和旅行按鈕的成本,它在450.0價格區域中增加了400.0。你沒有得到這個問題? – 2015-03-03 16:41:11
嗨,只是爲了確保您有興趣計算每加侖英里數和行程總成本。所以你做兩個計算: 英里/加侖使用= MPG和加侖*每加侖價格=總價格。當前總價格以紅色文本顯示在警報和MPG中。 對於這個例子230英里,9加侖,每加侖價格7.5美元總成本是9 * 7.5 = 67.5美元總成本和230/9 = 25.56 MPG 這是我的代碼會給你的結果。如果你想計算一些其他信息,請讓我知道。難道你是用「,」來代替「。」的花車。 ??? – mareklspak 2015-03-04 18:00:24