我一直在困扰这个问题一段时间了,我有一个计时器,当我拨打Stopwatch.start();
,Stopwatch.stop();
或{{1时,有4个按钮启动,停止,重置和圈数它工作得很好但是当我试图调用Stopwatch.reset();
时它不起作用!
我之前得到了答案,但现在我有一台新电脑和类似的东西,我无法调用该功能。控制台说“Uncaught TypeError:Stopwatch.lap不是一个函数”,我找不到问题。
这是我的代码:
Stopwatch.lap();
当我按下指定的键时,我需要调用lap功能,它看起来像这样:
var Stopwatch = {
init: function(elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
lapButton = createButton("lap", lap),
lapSpan = createTimer(),
offset,
clock,
interval;
options = options || {};
options.delay = options.delay || 1;
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
elem.appendChild(lapButton);
elem.appendChild(lapSpan);
reset();
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function lap() {
lapSpan.innerHTML=timer.innerHTML;
}
function reset() {
clock = 0;
render(0);
lap();
}
function update() {
clock += delta();
render();
}
function render() {
timer.innerHTML = clock / 1000;
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
this.getTime=function() {
return clock;
}
this.start = start;
this.stop = stop;
this.reset = reset;
}
};
var elems;
window.onload=function() {
elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
Stopwatch.init(elems[i]);
}
}
我最熟悉这个项目中的JavaScript和jQuery,但我也知道HTML和JavaScript。
答案 0 :(得分:4)
您确实在类/对象中定义了函数,忘记添加this.lap = lap;
,以便将其用作方法/属性。
应该是:
this.start = start;
this.stop = stop;
this.reset = reset;
this.lap = lap; // this one was missing
答案 1 :(得分:2)
您需要添加
this.lap = lap;
后面的行
this.start = start;
this.stop = stop;
this.reset = reset;