我试图获得new Date()
并使用原型自动显示div中的时间。但它不起作用。
<div></div>
Element.prototype.startTime
div.startTime('a word')
<div> 00:00:00 </div>
第二次更新
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
setTimeout(Element.prototype.startTime = function(t) {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
if (t === 'time') {
this.innerHTML = h + ":" + m + ":" + s;
}
if (t === 'minutes') {
this.innerHTML = m;
}
if (t === 'seconds') {
this.innerHTML = s;
}
}, 500);// Not Updating Properly
document.getElementById('display').startTime('time');
&#13;
<div id="display"></div>
&#13;
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime(t) {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
div = document.getElementById('display')
if (t === 'time') {
div.innerHTML = h + ":" + m + ":" + s;
}
if (t === 'minutes') {
div.innerHTML = m;
}
if (t === 'seconds') {
div.innerHTML = s;
}
setTimeout(function() {
startTime(t)
}, 500);
};
startTime('time');
&#13;
<div id="display"></div>
&#13;
答案 0 :(得分:1)
在setTimeout
中使用prototype
的主要问题是使用this
所以只需设置that = this
并使用that
变量......一切都会很好用。
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
Element.prototype.Today = function(t) {
let that = this
today = new Date()
h = checkTime(today.getHours());
m = checkTime(today.getMinutes());
s = checkTime(today.getSeconds());
if (t === 'time') {
that.innerHTML = h + ":" + m + ":" + s;
}
if (t === 'minutes') {
that.innerHTML = m;
}
if (t === 'seconds') {
that.innerHTML = s;
}
setTimeout(function() {
that.Today(t)
}, 500);
return this
};
div = document.getElementById('display')
div.Today('time')
<div id="display"></div>