当我尝试在另一个函数中使用函数的返回值时,我得到一个空字符串。我将函数值声明为变量,所以我不确定为什么要得到它。
const fnCalIn = calIn();
const fnCalOut = calOut();
//to get the value in the calIn input field and turn it into a number then print to page
function calIn() {
var calIn = document.getElementById("calIn").value;
var clCalIn = Number(calIn);
document.getElementById("demo-1").innerHTML = clCalIn;
return clCalIn;
};
//to get the value in the calOut input field and turn it into a number then print to page
function calOut() {
var calOut = document.getElementById("calOut").value;
var clCalOut = Number(calOut);
document.getElementById("demo-2").innerHTML = calOut;
return calOut;
};
// Where I want to get the difference of the calOut and calIn values and print that to the page
function calDt() {
var clCalDt = fnCalOut - fnCalIn;
document.getElementById("calDt").innerHTML = clCalDt;
}
<h1 class="current">Today</h1>
<div>
<h3>Calories in </h3>
<input id="calIn">
<button onclick="calIn()">Get value</button>
<p id="demo-1"></p>
</div>
<div>
<h3>Calories Out </h3>
<input id="calOut">
<button onclick="calOut()">Get value</button>
<p id="demo-2"></p>
</div>
<div>
<h3>Deficit </h3>
<div>
<p id="calDt"></p>
<button onclick="calDt()">Get value</button>
</div>
</div>
我一直得到0,当我将HTML更改为clCalDt时,我应该获得一些值,具体取决于我在输入字段中输入的内容,但是什么也没有。当我尝试记录值时,我得到一个空字符串“”。
答案 0 :(得分:3)
您在开始时仅调用一次函数(fnCalIn和fnCalOut),然后它们的值保持静态,并且页面中的任何更改都不会影响它们。尝试更改
var clCalDt = fnCalOut - fnCalIn;
收件人:
var clCalDt = calOut() - calIn();
以便重新计算值。
答案 1 :(得分:0)
问题。您正在返回return calOut;而不返回clCalOut,并且在计算中您需要调用函数。可能需要检查以确保输入的内容实际上是某个地方的数字。
//to get the value in the calIn input field and turn it into a number then print to page
function calIn() {
var calIn = document.getElementById("calIn").value;
var clCalIn = Number(calIn);
document.getElementById("demo-1").innerHTML = clCalIn;
return clCalIn;
};
//to get the value in the calOut input field and turn it into a number then print to page
function calOut() {
var calOut = document.getElementById("calOut").value;
var clCalOut = Number(calOut);
document.getElementById("demo-2").innerHTML = calOut;
return clCalOut;
};
// Where I want to get the difference of the calOut and calIn values and print that to the page
function calDt() {
var clCalDt = calOut() - calIn();
document.getElementById("calDt").innerHTML = clCalDt;
}
<h1 class="current">Today</h1>
<div>
<h3>Calories in </h3>
<input id="calIn">
<button onclick="calIn()">Get value</button>
<p id="demo-1"></p>
</div>
<div>
<h3>Calories Out </h3>
<input id="calOut">
<button onclick="calOut()">Get value</button>
<p id="demo-2"></p>
</div>
<div>
<h3>Deficit </h3>
<div>
<p id="calDt"></p>
<button onclick="calDt()">Get value</button>
</div>
</div>