我正在尝试从这个 jQuery Stopwatch 库获取毫秒值 https://github.com/robcowie/jquery-stopwatch
除了 GitHub 问题中指出的以外,毫秒值没有记录
Make elapsed milliseconds available in data. #2 … Get at it with $().data('stopwatch')['elapsed']
我尝试通过以下代码以这种方式访问毫秒(它在 Wordpress 中,因此缺少 $ 符号)
<a href="#" id="test"><h2>Test</h2></a>
<script>
jQuery( "#test" ).click(function() {
alert(jQuery().data('stopwatch')['elapsed']);
});
</script>
但是我收到以下控制台错误
Uncaught TypeError: Cannot read property 'elapsed' of null
秒表通过此代码初始化
jQuery( document ).ready(function($) {
setTimeout(function(){ $('.quizTimerSpan').stopwatch({startTime: 0, format: '{MM}:{ss}'}).stopwatch('start') }, 8500);
});
第一个问题实际上是获取毫秒值,然后在单击按钮时将其实际传递给输入值。我假设一旦我实际获得毫秒值,下面的代码就可以工作,但我对 jQuery 还很陌生,所以最好也检查一下这个健全性。
jQuery( "#question" ).submit(function( event ) {
jQuery( "#timerValue" ).val(.data('stopwatch')['elapsed']));
event.preventDefault();
});
HTML 表单元素...
<input type="hidden" name="timerValue" id="timerValue" value="" />
最佳答案
通过从这里切换到 jQuery Timer 库,我已经成功实现了我想要做的事情 http://jchavannes.com/jquery-timer/demo
下面的代码正是我所需要的......
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
function formatTime(time) {
time = time / 10;
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
// Switch for more accurate output
// return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2);
}
var quizStopwatch = new (function() {
var $stopwatch;
var incrementTime = 70;
var currentTime = 0;
$(function() {
$stopwatch = $('.quizTimerSpan');
quizStopwatch.Timer = $.timer(updateTimer, incrementTime, true);
});
function updateTimer() {
var timeString = formatTime(currentTime);
$stopwatch.html(timeString);
currentTime += incrementTime;
document.title = timeString;
$("#timerValue").val(currentTime);
}
});
作为奖励,我还可以在每个时间间隔设置页面标题。
关于javascript - 使用 jQuery Stopwatch 将毫秒从计时器传递到表单提交的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23906817/