簡體   English   中英

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

[英]Local Variable to Global Variable in JavaScript

我正在開發一個 web 頁面,在從輸入字段輸入日期后,將計算月份。

我想將“diffMonthsGlobe”的值帶到另一個 function,這個計算值將進入數據庫。

但是正如我在 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. 使用表格以便所需的工作
  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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM