Cash Register App I'm Making(log on upper right corner)
我正在制作一个简单的收银网络应用程序,用于计算和记录手动项目输入。我的java脚本函数执行onclick并将HTML单击日期时间信息添加到HTML日志中。但是正确的日期/时间仅在第一次记录,下一次是第一次重复。没有更新。
下面的变量示例
document.getElementById("logger").addEventListener("click", function(){
logData();
});
function logData() {
var now = new Date();
var profit = 0;
var month = now.getMonth() + 1;
var day = function() {
return now.getDate();
};
var year = function() {
return now.getFullYear();
};
var hour = function() {
return now.getHours();
};
var minute = function() {
return now.getMinutes();
};
var seconds = function() {
return now.getSeconds();
};
var trStart = "<tr>";
var tdStart = "<td>";
var tdEnd = "</td>";
var trEnd = "</tr>";
document.getElementById("log").innerHTML += trStart + tdStart + month + "/" + day() + "/" + year() + tdEnd + tdStart + hour() + ":" + minute() + ":" + seconds() + tdEnd + tdStart + "$" + 'last' + tdEnd + trEnd;
}
<div id="logger">Click</div>
<table id="log"></table>
答案 0 :(得分:3)
变量&#39;现在&#39;声明并在开始时设置,然后由后续函数引用。要更新,您必须拨打新的日期()&#39;每个函数内部的方法,而不是像以前声明的那样引用变量。
答案 1 :(得分:0)
您的变量不会自动更新,您需要使用以下功能:
(function() {
function getDate() {
let _now = new Date();
return {
month: _now.getMonth() + 1,
day: _now.getDate(),
year: _now.getFullYear(),
hour: _now.getHours(),
minute: _now.getMinutes(),
seconds: _now.getSeconds()
}
}
let log = document.getElementById("log");
function clearLog() {
log.innerHTML = "";
}
function changeLog() {
let newDate = getDate(),
last = "{{ last }}";
log.innerHTML += "<tr>" + "<td>" + newDate.month + "/" + newDate.day + "/" + newDate.year + "</td>" + "<td>" +
newDate.hour + ":" + newDate.minute + ":" + newDate.seconds + "</td>" + "<td>" + "$" + last + "</td>" + "</tr>";
}
function _initEvents() {
document.getElementById('get-log').addEventListener('click', function() {
clearLog();
changeLog();
});
}
_initEvents();
})();
&#13;
<div id="log"></div>
<button id="get-log">Get Log</button>
&#13;
然后致电: