我的问题是它登录控制台2次。我搞不清楚出了什么问题。如果它同时在If和else部分执行代码,它会记录小时+0+分钟,然后是正常时间。它并没有这样做,它只执行了它应该执行的2次。
function GtD() {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
if (minute >= 0 && minute <= 9) {
console.log(hour + ":" + "0" + minute);
} else {
console.log(hour + ":" + minute);
}
}
<button onclick="getElementById(GtD()), GtD()">
Click to get the current time
</button>
仅仅因为您已经调用了两次函数
让我们看看您的HTML:
<button onclick="getElementById(GtD()), GtD()">
Click to get the current time
</button>
更具体地说
onclick="getElementById(GtD()), GtD()"
您调用getElementById
时将GtD()
作为参数。这将调用您的GtD
函数一次。然后在getElementById
之后调用GtD()
。所以自然会有两个控制台日志。这可以简单地更改为以下
function GtD() {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
if (minute >= 0 && minute <= 9) {
console.log(hour + ":" + "0" + minute);
} else {
console.log(hour + ":" + minute);
}
}
<button onclick="GtD()">
Click to get the current time
</button>
您在onclick元素中执行了两次函数。
更改为<button onclick="GtD()">
您调用了两次
在onclick中包含了getElementByID(Gtd())
,这没有意义,因为函数GtD()
没有返回值。您不需要通过ID获取元素。您只需要登录到控制台。
忽略这一点:
<button onclick="GtD()">
Click to get the current time
</button>