我有以下Javascript代码,无法获取警报消息原因?我怎样才能解决这个问题?感谢您的回复。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="date" id="mydate">
<p id="current"></p>
<script>
document.getElementById('myDate').onchange = function () {
var selectedDateFromCalendar = this.value;
var currentdate = new Date();
document.getElementById("current").textContent = currentdate.toUTCString();
// get difference in milliseconds
var Diff = Math.abs(currentdate.getTime() - selectedDateFromCalendar.getTime());
// Convert it into days
var diffDays = Math.ceil(Diff / (1000 * 3600 * 24));
alert(diffDays);
}
</script>
</body>
答案 0 :(得分:1)
您需要收听oninput
事件。您还可以检查onchange
和其他事件。 This post很有帮助。
此外,日期<input>
具有valueAsDate
属性,可返回日期对象。
注意: 我使用console.log
而不是alert
,因为Stack代码段不允许alert
。
document.getElementById('myDate').oninput = function() {
var selectedDateFromCalendar = this.value;
var currentdate = new Date();
document.getElementById("current").textContent = currentdate.toUTCString();
// Get difference in milliseconds.
var diff = Math.abs(currentdate.getTime() - this.valueAsDate.getTime());
// Convert it into days.
var diffDays = Math.ceil(diff / (1000 * 3600 * 24));
console.log(diffDays);
}
<input type="date" id="myDate" />
<p id="current"></p>
答案 1 :(得分:0)
我已经添加了一些代码并且工作正常
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="date" id="mydate" onchange="dates()">
<p id="current"></p>
<script>
function dates () {
var selectedDateFromCalendar = this.value;
var currentdate = new Date();
document.getElementById("current").textContent = currentdate.toUTCString();
// get difference in milliseconds
var Diff = Math.abs(currentdate.getTime() - (new Date()).getTime());
// Convert it into days
var diffDays = Math.ceil(Diff / (1000 * 3600 * 24));
alert(diffDays);
}
</script>
</body>
</html>