为什么代码不能正常工作JS?

时间:2015-12-21 11:29:53

标签: javascript html

我有以下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>    

2 个答案:

答案 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>