gpt4 book ai didi

javascript - 在定时器中调用 lap 函数

转载 作者:行者123 更新时间:2023-11-30 08:00:11 25 4
gpt4 key购买 nike

我已经为这个问题烦恼了一段时间,我有一个计时器,它有 4 个按钮开始、停止、重置和圈数,当我调用 Stopwatch.start(); 时,Stopwatch.stop();Stopwatch.reset(); 它工作正常但是当我尝试调用 Stopwatch.lap(); 它不起作用!

我以前有答案,但现在我有一台新电脑和类似的东西,我无法调用该函数。控制台显示“Uncaught TypeError: Stopwatch.lap is not a function”,我找不到问题所在。

这是我的代码:

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]);
}
}

当我按下指定的键时,我需要调用 lap 函数,它看起来像这样:

document.onkeypress = function(e) {
e = e || window.event;
var charCode = e.charCode || e.keyCode,
character = String.fromCharCode(charCode);

if(e.charCode == 98 || e.keyCode == 98) {
Stopwatch.start();

} else if(e.charCode == 114 || e.keyCode == 114) {
Stopwatch.lap();

}
};

我在这个项目中最熟悉 JavaScript 和 jQuery,但我也知道 HTML 和 JavaScript。

最佳答案

您确实在类/对象中定义了函数,但您忘记添加 this.lap = lap; 因此您可以将其用作方法/属性。

应该是:

this.start = start;
this.stop = stop;
this.reset = reset;
this.lap = lap; // this one was missing

关于javascript - 在定时器中调用 lap 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com