在函数中使用返回值

时间:2019-07-05 13:47:10

标签: html css

我将函数分配给了一个变量。这是正确的方法吗?我想访问返回值,以便可以在另一个函数中使用它来计算卡路里不足。

html

<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>

JavaScript

 var fnCalIn = calIn();

function calIn() {
  var calIn = document.getElementById("calIn").value;
  var clCalIn = Number(calIn);
  console.log(clCalIn);
  document.getElementById("demo-1").innerHTML = clCalIn;
  return clCalIn ;
};


var fnCalOut = calOut();
function calOut() {
  var calOut = document.getElementById("calOut").value;
  var clCalOut = Number(calOut);
  console.log(clCalOut);
  document.getElementById("demo-2").innerHTML = calOut;
  return calOut ;
};


function calDt(){
//My function trying to calculate the difference using the return values from the functions 
  // var clCalDt = fnCalOut - fnCalIn;

}

1 个答案:

答案 0 :(得分:0)

function getValue() {
  const calIn = document.getElementById("calIn").value;
  const clCalIn = Number(calIn);
  console.log(clCalIn); 
  return clCalIn;
}

document.querySelector('#get-value').addEventListener('click', getValue);
<h1 class="current">Today</h1>
<div>
  <h3 >Calories in </h3>
  <input id ="calIn"></input>
</div>

<button id="get-value">Get value</button>