javascript - 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()" />
解决方案
- 使用表格,以便所需的作品
- 使用提交事件获取值并发送到服务器
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>
推荐阅读
- c# - Serilog - 缺少参数的警告
- node.js - 不能在 $or 中使用 $in 吗?
- javascript - 我不理解使用字符串和布尔值的逻辑运算符
- javascript - 倒数计时器暂停/恢复功能javascript
- android - 在应用程序的一个实例中安装所有构建类型,并允许在运行时选择构建类型
- html - 部分 SVG 蒙版不透明且颜色反转
- c# - Autofac注册具体类
- boost - Boost Spirit x3 在直接解析时插入空字符串
- c# - 跨类访问方法
- c# - 如何使用 Selenium webdriver 在 Internet Explorer 上获取 cookie - C#