简体   繁体   English

JavaScript 中的局部变量到全局变量

[英]Local Variable to Global Variable in JavaScript

I am developing a web page where the Months will be calculated after entering the Date from the Input Field.我正在开发一个 web 页面,在从输入字段输入日期后,将计算月份。

I want to take the value of "diffMonthsGlobe" to another function where this calculated value is going to the database.我想将“diffMonthsGlobe”的值带到另一个 function,这个计算值将进入数据库。

But as I have seen few answers in StackOverflow and try to do the same but still in my case it is not possible但是正如我在 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()" />

  1. Use a form so the required works使用表格以便所需的工作
  2. Use the submit event to get the value and send to server使用提交事件获取值并发送到服务器

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM