[英]Simple JavaScript function returns function and not value
我只是剛開始,正在嘗試構建一個簡單的計算功能,該功能將在頁面上顯示2個數字的結果。 單擊提交按鈕時,輸出是函數而不是值。 我哪里出問題了?
的HTML
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
JS
<script>
'use strict';
var total = function() {
var price = function() {
parseFloat(document.getElementById("price"));
}
var tax = function() {
parseFloat(document.getElementById("tax"));
}
var final = function() {
final = price * tax;
final = total
}
document.getElementById("output").innerHTML = final;
};
</script>
您的javascript有幾個問題。 讓我們一一分解它們:
var price = function() { parseFloat(document.getElementById("price")); }
document.getElementById
返回一個元素。 parseFloat
會嘗試計算元素,而不是這種情況下的值(始終為NaN或非數字)。 您需要此元素的值,因此使用.value
將返回該值。 此外,您實際上並沒有對值做任何事情。 (您應該使用return返回找到的浮點數,或將其設置為另一個變量。)
var final = function() { final = price * tax; final = total }
在這種情況下, price
和tax
都是功能。 您不能簡單地將它們相乘以獲得所需的結果。 使用var total = price() * tax();
現在將變量total
設置為price()
和tax()
返回的浮點數。 將此值返回給函數將修復下一行:
document.getElementById("output").innerHTML = final;
final
這里也是一個功能。 您想通過使用final()
來調用它。
您的最終腳本:
var total = function() { var price = function() { return parseFloat(document.getElementById("price").value); } var tax = function() { return parseFloat(document.getElementById("tax").value); } var final = function() { var total = price() * tax(); return total } document.getElementById("output").innerHTML = final(); };
<div id="input"> <form id="start"> <input id="price" type="number" placeholder="What is the starting price?" value="10"> <input id="tax" type="number" value="0.08" step="0.005"> </form> <button type="button" form="start" value="submit" onClick="total()">Submit</button> </div> <div id="output">test</div>
您有幾個問題,您將一些代碼放入函數中而不調用它們。
另一個問題是,您需要輸入標簽的值。
'use strict'; var total = function() { var price = parseFloat(document.getElementById("price").value); // get value ^^^^^^ var tax = parseFloat(document.getElementById("tax").value) // get value ^^^^^^ // calculate directly the final value var final = price * tax; document.getElementById("output").innerHTML = final; };
<div id="input"> <form id="start"> <input id="price" type="number" placeholder="What is the starting price?" value="10"> <input id="tax" type="number" value="0.08" step="0.005"> </form> <button type="button" form="start" value="submit" onClick="total()">Submit</button> <div id="output"></div>
刪除
var final = function() {
final = price * tax;
final = total
}
而是放
return price * tax;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.