gpt4 book ai didi

javascript - 将 JavaScript 值放入变量中

转载 作者:行者123 更新时间:2023-11-27 23:41:51 25 4
gpt4 key购买 nike

我 14 岁的儿子正在研究 react 时间和年龄的科学项目。他正在设置一个小网络应用程序来测试人们 - 当页面加载时,计时器启动,并且“停止”按钮出现延迟(本例为 4 秒)。当他们单击停止按钮时,计时器停止。到目前为止,他在所有这些方面都完成了出色的编码工作。他正在使用他发现的一段 JavaScript,并根据自己的需要对其进行了修改。
他的问题 - 如何将停止的时间传递到变量中,然后将其传递到另一个页面。如果变量是静态的,即“Hello”,他就能够成功完成此操作。函数 stop() 有什么问题;在这个例子中?他当前获得了一个 [object HTMLSpanElement]

var clsStopwatch = function() {
// Private vars
var startAt = 0; // Time of last start / resume. (0 if not running)
var lapTime = 0; // Time on the clock when last stopped in milliseconds

var now = function() {
return (new Date()).getTime();
};

// Public methods
// Start or resume
this.start = function() {
startAt = startAt ? startAt : now();
};

// Stop or pause
this.stop = function() {
// If running, update elapsed time otherwise keep it
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0; // Paused
};

// Reset
this.reset = function() {
lapTime = startAt = 0;
};

// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};

var x = new clsStopwatch();
var $time;
var clocktimer;

function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}

function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';

h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;

newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}

function update() {
$time.innerHTML = formatTime(x.time());
}

function start() {
$time = document.getElementById('time');
update();
clocktimer = setInterval("update()", 1);
x.start();
$(document).ready(function() { $('#mybutton').delay(4000).fadeIn(0);});
}

function stop() {
x.stop();
//var varTime = "Hello";
var varTime = document.getElementById('time');
window.location.href = "somephpfile.php?etime=" + varTime;


}

最佳答案

var varTime = document.getElementById('time')正在将元素分配给变量,这很好,而且不是一个坏选择,但我相信您的儿子只需要该元素的 HTML 文本。

有两个选项。第一个选项保留 time函数中的元素以便以后可能进行扩展。

function stop() {
x.stop();
var varTime = document.getElementById('time');
if (varTime) {
window.location.href = "somephpfile.php?etime=" + varTime.innerHTML;
}
}

或者只是提取所需的文本并发送 - 即使它是空的。

function stop() {
x.stop();
if (document.getElementById('time')) {
window.location.href = "somephpfile.php?etime=" + document.getElementById('time').innerHTML;
}
}

关于javascript - 将 JavaScript 值放入变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33590239/

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