初学者JS,功能不起作用

时间:2017-04-14 21:34:21

标签: javascript html

所以我是JavaScript的新手 - 就像“new”中的几天一样,我不明白为什么我打电话的这个功能不起作用。

我有这个HTML页面:

<!doctype html>
<html>
<head>
<title>Document</title>
</head>
<body>

  <h1>Practice</h1>
  <button id="btn" onclick="printDate()">Print Date</button>
  <p id="Day"></p>
  <button onclick="printTime()"> Show Clock </btn>
  </br>
  <p id="Time"></p>
  <script src="Clock.js"></script>

</body>
</html>

而clock.js有以下内容:

// Defines Function

function printDate() {

// Grabs values from "Date" object using various methods

   var date = new Date();
   var day = date.getDay();
   var dateNum = date.getDate();
   var month = date.getMonth();
   var year = date.getYear();

// Corrects for JS year format

   year += 1900

// Switch "day" value with string containing name of day

   switch(day){

case 0: day = "Sunday"
break;
case 1: day = "Monday"
break;
case 2: day = "Tuesday"
break;
case 3: day = "Wednesday"
break;
case 4: day = "Thursday"
break;
case 5: day = "Friday"
break;
case 6: day = "Saturday"
break;
}

// Switch "month" value with string containing name of month

   switch(month){

case 0: month = "January"
break;
case 1: month = "February"
break;
case 2: month = "March"
break;
case 3: month = "April"
break;
case 4: month = "May"
break;
case 5: month = "June"
break;
case 6: month = "July"
break;
case 7: month = "August"
break;
case 8: month = "September"
break;
case 9: month = "October"
break;
case 10: month = "November"
break;
case 11: month = "December"
break;
}

// Prints values into p tag ID'd with "Day"

document.getElementById("Day").innerHTML = "Today is: "+day+" the "+dateNum+" of "+month+", "+year

}

function printTime() {

document.getElementById("Time").innerHTML = "Current Time"

}

对不起评论,这些都是出于我自己的学习目的。

所以对于这个问题 - 当我尝试在HTML文档中调用printTime()时,它不起作用,并且不会用“当前时间”替换innerHTML,但是,另一个函数工作正常。我在这做错了什么?为什么第一个功能起作用,而不是第二个?

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

该按钮的结束标记不正确。如果</btn>,则</button>为{{1}}。

答案 1 :(得分:2)

关闭主题:只需对脚本进行一些重构

var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

function printDate() {
    // Grabs values from "Date" object using various methods
    var date = new Date();
    var dateNum = date.getDate();   
    var day = weekdays[date.getDay()];
    var month = months[date.getMonth()];
    var year = date.getFullYear();

    // Prints values into p tag ID'd with "Day"
    document.getElementById("Day").innerHTML = "Today is: "+day+" the "+dateNum+" of "+month+", "+year;
}

function printTime() {
    document.getElementById("Time").innerHTML = "Current Time"
}