//我试图以英尺输入米为单位获得结果。
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
//对于我输入的任何数字,我得到0作为答案。
var feetInput = document.getElementById("feet-input").value;
var result = document.getElementById("result");
var total;
function calculate(){
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
对于任何数字,我输入0作为答案。
答案 0 :(得分:1)
因为您的var feetInput = document.getElementById("feet-input").value;
仅在您需要在函数调用中获取最新值时执行,如下所示
//var feetInput = document.getElementById("feet-input").value;//only executed once
var result = document.getElementById("result");
var total;
function calculate(){
var feetInput = document.getElementById("feet-input").value;
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
答案 1 :(得分:0)
唯一的问题是,只有在加载页面时才会读取feet-input
的值。
在进行计算之前,您需要获取feet-input
的值。
只需在var feetInput = document.getElementById("feet-input").value;
function calculate(){
添加到该行
Codepen:https://codepen.io/DeathCamel57/pen/xPPGrp?editors=0010