将函数结果调用到Web文档

时间:2016-01-04 22:57:01

标签: javascript html5

所以我对HTML和编程完全陌生。我正在努力为学校作业完成一个问题而且我遇到了很多麻烦。我已经阅读了这个教程并且搜索了很多内容,我似乎无法弄明白。

我有这个功能:

function showDate() {
  thisDate = new Date();
  var thisWDay=thisDate.getDay();
  var thisDay=thisDate.getDate();
  var thisMonth=thisDate.getMonth();
  var thisYear=thisDate.getFullYear();
  var mName = new Array("January", "February", "March", "April", "May", 
    "June", "July", "August", "September", "October","November", "December");
  var wdName = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday");
  return wdName[thisWDay]+", "+mName[thisMonth]+" "+thisDay+", "+thisYear;
}

我需要在Web文档中显示此功能的输出。 我正在按照教程,但它没有看到想要工作。我知道我做错了什么。 这就是我所拥有的:

<script type="text/javascript">
  function showDate();
  document.write("Today is <b> " + showDate() + "</b>");
</script>

我知道这可能非常简单,但是对于正确方向的任何推动都会非常感激。

2 个答案:

答案 0 :(得分:2)

试试这个:

function showDate() {
  var thisDate = new Date();
  var thisWDay = thisDate.getDay();
  var thisDay = thisDate.getDate();
  var thisMonth = thisDate.getMonth();
  var thisYear = thisDate.getFullYear();
  var mName = new Array("January", "February", "March", "April", "May",
    "June", "July", "August", "September", "October", "November", "December");
  var wdName = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday");
  return wdName[thisWDay] + ", " + mName[thisMonth] + " " + thisDay + ", " + thisYear;
}

您将在函数调用后设置变量。

<script type="text/javascript">
var dt = showDate();
document.write("Today is <b> " + dt + "</b>");
</script>

答案 1 :(得分:0)

此代码无效,因此如果您检查浏览器的开发者控制台(通常按F12打开),则可能会导致错误,这会阻止其余代码执行。

function showDate();

这可能会导致您的问题。我不确定您的意图是什么,但是当您使用function关键字时,您表明您正准备定义新功能。您已经定义了showDate;虽然你没有把它包含在你的第二个片段中。

将第二个代码段中的function showDate();替换为第一个代码段中的定义,它应该可以使用。它应该看起来像:

<script type="text/javascript">
    function showDate() {
        var thisDate = new Date();
        var thisWDay=thisDate.getDay();
        var thisDay=thisDate.getDate();
        var thisMonth=thisDate.getMonth();
        var thisYear=thisDate.getFullYear();
        var mName = new Array("January", "February", "March", "April", "May",  "June", "July", "August", "September", "October","November", "December");
        var wdName = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
        return wdName[thisWDay]+", "+mName[thisMonth]+" "+thisDay+", "+thisYear;
    }

    document.write("Today is <b> " + showDate() + "</b>");
</script>