首页 > 解决方案 > JavaScript 中的局部变量到全局变量

问题描述

我正在开发一个网页,在输入字段中输入日期后将计算月份。

我想将“diffMonthsGlobe”的值带到另一个函数,该计算值将进入数据库。

但是正如我在 StackOverflow 中看到的几个答案并尝试做同样的事情但在我的情况下仍然是不可能的

 var diffMonthsGlobe;

function getValue() {
  // Getting Values......

  const startDate = document.getElementById("startDate").value;
  const endDate = document.getElementById("endDate").value;

  // Calculating Time Period.......

  const date1 = new Date(endDate);
  const date2 = new Date(startDate);

  var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
  diffMonth /= 60 * 60 * 24 * 7 * 4;

  diffMonths = Math.abs(Math.round(diffMonth));

  diffMonthsGlobe = diffMonths;
  
  // Printing Values......

  console.log(startDate);
  console.log(endDate);
  console.log(diffMonths + " Months");
  
  return diffMonthsGlobe;
}

getValue();
console.log(diffMonthsGlobe + " Months");
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required onchange="getValue()" />

<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required onchange="getValue()" />

标签: javascripthtml

解决方案


  1. 使用表格,以便所需的作品
  2. 使用提交事件获取值并发送到服务器

const getValue = function() {
  // Getting Values......

  const startDate = document.getElementById("startDate").value;
  const endDate = document.getElementById("endDate").value;

  // Calculating Time Period.......

  const date1 = new Date(endDate);
  const date2 = new Date(startDate);

  var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
  diffMonth /= 60 * 60 * 24 * 7 * 4;

  diffMonths = Math.abs(Math.round(diffMonth));

  diffMonthsGlobe = diffMonths;

  // Printing Values......

  console.log(startDate);
  console.log(endDate);

  return diffMonthsGlobe;
}

window.addEventListener("load", function() { // page load
  document.getElementById("myForm").addEventListener("submit", function(e) {
    e.preventDefault(); // stop submission
    const monthDiff = getValue();
    console.log(monthDiff + " Months");
    // here you can fetch or otherwisde ajax to server
  })
})
<form id="myForm">
  <input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required />

  <input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required />

  <input type="submit" />
</form>


推荐阅读