簡體   English   中英

從計時器傳遞毫秒到使用jQuery Stopwatch在表單提交上輸入

[英]Pass milliseconds from timer to input on form submit with jQuery Stopwatch

我正在嘗試從這個jQuery秒表庫https://github.com/robcowie/jquery-stopwatch獲得毫秒值

毫秒值未記錄,除了在GitHub問題中指出

使經過的毫秒數在數據中可用。 #2…使用$()。data('stopwatch')['elapsed']

我試圖通過以下代碼以這種方式訪問​​毫秒(它在Wordpress中,因此缺少$符號)

<a href="#" id="test"><h2>Test</h2></a>
<script>
    jQuery( "#test" ).click(function() {
        alert(jQuery().data('stopwatch')['elapsed']);
    });
</script>

但是我收到以下控制台錯誤

未被捕獲的TypeError:無法讀取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="" />

通過從這里http://jchavannes.com/jquery-timer/demo切換到jQuery Timer庫,我設法實現了我想做的事情

以下代碼正是我所需要的...

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

作為獎勵,我還可以在每個間隔上設置頁面標題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM