测量输入时间

时间:2015-04-02 16:11:36

标签: javascript jquery time measure

我有一个简单的测验表格,有几个输入和选择,我需要衡量参赛者写/选择答案的时间。

这就是我正在尝试的,但报告的时间不正确:



$('input, select').on('focus', function(event) {

    el = $(this);

    name = el.attr('name'); // console.log(name);
    a = performance.now();
    a_value = el.val();

    console.log(name + ' focused.');

    $(el).on('input select cut copy paste', function(event) {
        console.log('el: ' + el);
        b_value = el.val();
        if (a_value != b_value) {
            b = performance.now();
            if (name in times) {
                console.log('exists');
                times[name] = times[name] + (b - a);
            } else {
                times[name] = b - a;
            }
        }
    });

    $(el).on('blur', function(event) {
        alert(times);
    });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

  <input type="text" name="" id="">
  <select name="" id="">
    <option value="">option1</option>
    <option value="">option2</option>
  </select>
  
</body>
</html>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

在与您(OP)交谈后,我对您的基本代码做了一些调整。

首先,每次表单元素具有焦点时都会调用.on('input ...'),以便事件处理程序堆叠起来。在模糊处理程序中调用相应的.off('input ...')来处理此问题。

接下来,要在JavaScript中创建关联数组,我们通常使用对象,因此我创建了times = {}

接下来,times[name] = times[name] + (b - a);在首次关注元素时继续使用a的初始时间值,因此聚合时间会快速堆叠。我们可以通过之后设置a = b;来弥补这一点。

最后,为了跟踪选择的更改时间与输入更改时的更改,我们可以在选择更改时更新内部选定值,如a_value = b_value;

我希望这就是你要找的东西。

&#13;
&#13;
var times = {};
$('input, select').on('focus', function(event) {
  var el = $(this);

  // This will get the name of the input or select. Is that right?
  // OP: yes, this becomes the key in the array
  var name = el.attr('name');
  var a = performance.now();
  var a_value = el.val();

  // This will attach an event handler over and over unless we 
  // unattach it. Please see "blur" below
  el.on('input select cut copy paste', function(event) {
    var b_value = el.val();

    // Initial values are updated as inputs change
    // so the times don't stack up
    if (a_value !== b_value) {
      b = performance.now();
      if (times.hasOwnProperty(name)) {
        console.log('exists');
        times[name] = times[name] + (b - a);
        a = b;
      } else {
        console.log('adding ' + name);
        times[name] = b - a;
      }
      a_value = b_value;
    }
  });

  el.one('blur', function(event) {
    console.dir(times);

    // Update the times display
    displayTimes();

    // Unattach the event handler added in on("focus")
    el.off('input select cut copy paste');
  });

  // For the demo
  function displayTimes() {
    // Output results
    var str = "";
    $.each(times, function(key, value) {
      str += key + " total time: " + value + "<br>";
    });
    $("#results").html(str);
  }

  // Periodically update the times just for the demo
  setInterval(displayTimes, 200);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input" id="">
<select name="select" id="">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
</select>
<div id="results"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个..

<script>
  var Stopwatch = (function() {
            var s;
            return {
                settings: {
                    stop: 0,
                    sw: document.querySelectorAll(".stopwatch")[0],
                    results: document.querySelectorAll(".results")[0],
                    mills: 0,
                    secs: 0,
                    mins: 0,
                    i: 1,
                    times: ["00:00:00"],
                    clearButton: "<a href=\"#\" class=\"button\" onClick=\"Stopwatch.clear();\">Clear</a>"
                },
                init: function() {
                    s = this.settings;
                    setInterval(this.timer, 1);
                },
                clear: function() {
                    s.i = 1,
                    s.times = ["00:00:00"],
                    s.results.innerHTML = s.clearButton;
                },
                lap: function() {
                    if (s.i === 1) {
                        s.results.innerHTML = s.clearButton;
                    }
                    s.times.push(("0" + s.mins).slice(-2) + ":"
                                         + ("0" + s.secs).slice(-2) + ":"
                                         + ("0" + s.mills).slice(-2));
                    var diffTime = ("0" + Math.floor(s.times[s.i].split(":")[0]
                                             - s.times[s.i-1].split(":")[0])).slice(-2)
                                             + ":"
                                             + ("0" + Math.floor(s.times[s.i].split(":")[1]
                                             - s.times[s.i-1].split(":")[1])).slice(-2)
                                             + ":"
                                             + ("0" + (s.times[s.i].split(":")[2]
                                             - s.times[s.i-1].split(":")[2])).slice(-2);
                    s.results.innerHTML = s.results.innerHTML + "<tr><td>"
                                                            + s.times[s.i] + "</td><td>"
                                                            + diffTime + "</td></tr>";
                    s.i++;
                },
                restart: function() {
                    s.mills = 0,
                    s.secs = 0,
                    s.mins = 0;
                    this.start();
                },
                start: function() {
                    s.stop = 0;
                },
                stop: function() {
                    s.stop = 1;
                },
                timer: function() {
                    if (s.stop === 0) {
                        if (s.mills === 100) {
                            s.secs++;
                            s.mills = 0;
                        }
                        if (s.secs === 60) {
                            s.mins++;
                            s.secs = 0;
                        }
                        s.sw.innerHTML = ("0" + s.mins).slice(-2) + ":"
                                                     + ("0" + s.secs).slice(-2) + ":"
                                                     + ("0" + s.mills).slice(-2);
                        s.mills++;
                    }
                }
            };
        })();
$('.textbox,.selectbox').focusin(function(event) {
 Stopwatch.init();
Stopwatch.restart();    
});
$('.textbox,.selectbox').on('blur', function(event) {
    Stopwatch.stop();
});

Working Fiddle Here

References

答案 2 :(得分:1)

我为此制作了简单的jquery插件。它能够告诉您总编辑时间是什么(仅在编辑实际使用时),第一个编辑时间和任何输入元素的上次编辑时间。您还可以获得所有编辑时间。

$('#number').on('keyup', function () {
changenumber(this.value);
});
$('#number').on('paste', function () {
changenumber(this.value);
});
var now = 0;
function changenumber(val) {
container = document.getElementById("container");
var diff = val - now;
if (diff > 0) {
    for (var u = now + 1; u <= val; u++) {
        container.innerHTML = container.innerHTML +
            " Select from options <select onchange='updateDom(this)' id='selectobj" + u + "' name='selectobj" + u + "' style='width:25%;'>" +
            "<option>A</option>" +
            "<option>B</option>" +
            "<option>C</option>" +
            "</select><br><br>";    now = u;
    }
}
}
function updateDom(s){
s.options[s.selectedIndex].setAttribute("selected","selected")

}

示例用法(fiddle):

(function () {
    var getTime = function () { return performance.now(); };
    function MeasureTime () {
        this.editTimes = [];
        this.currentEdit = null;
        this.lastEdit = {start:0, last: 0};
        this.firstEdit = 0;
    }
    MeasureTime.prototype = {
        setFirst: function () {
            this.firstEdit = getTime();
            this.setFirst = new Function();
        },
        startEdit: function (val) {
            this.setFirst();
            if(this.currentEdit == null) {
                this.currentEdit = {start: getTime(), last: getTime(), value: val};
                this.editTimes.push(0);
            } else {
                this.edit(val);
            }
        },
        edit: function (val) {
            if(this.currentEdit == null)
                  this.startEdit(val);
            else {
                var current = this.currentEdit;
                if(current.value == val)
                    return;
                current.last = getTime();
                this.editTimes.pop();
                this.editTimes.push(current.last - current.start);
            }
        },
        stopEdit: function () {
            if(this.currentEdit != null) {
                this.lastEdit = this.currentEdit;
                this.currentEdit = null;
            }
        },
        getEvent: function () {
            return new TimeMeasuredEvent(this.editTimes, this.currentEdit || this.lastEdit, this.firstEdit);
        }
    };
    function TimeMeasuredEvent (all, current, first) {
        this.all = all.slice(0);
        this.start = current.start;
        this.last = current.last;
        this.first = first;
    }
    TimeMeasuredEvent.prototype = {
        current: function () {
            return this.all[this.all.length-1];
        },
        total: function () {
            var sum = 0, a = this.all, l = a.length, i = -1;
            while(++i<l)
                sum+=a[i];
            return sum;
        }
    };
    function EnsureMeasureTime () {
        if (typeof(this.measureTimeData) === "undefined") {
            var mtd = this.measureTimeData = new MeasureTime();
            $(this).on('focus', function () {
                mtd.startEdit(this.value);
        $(this).on('input.measuretime select.measuretime cut.measuretime copy.measuretime paste.measuretime', function () {
           mtd.edit(this.value);
           $(this).trigger('timeMeasured', [mtd.getEvent()]); 
        });
            $(this).on('blur', function () {
                mtd.stopEdit();
                $(this).trigger('timeMeasured', [mtd.getEvent()]); 
                $(this).off('measuretime');
            });
        });
        }
    }
    $.fn.measureTime = function () {
        $(this).each(EnsureMeasureTime);
        return this;
    };
})();

您还可以var inputs = $('input, select'); inputs.measureTime(); var all = {}; inputs.on('timeMeasured', function (ev, data) { console.log(ev, data); all[ev.target.name] = data.total(); console.log("First edit time: " + data.first); console.log("Last edit time: " + data.last); console.log("All edits durations: " + data.all.join(", ")); console.log("Current edit duration: " + data.current()); console.log("Total edit duration: " + data.total()); var s = ""; for(var n in all) { s+= n + ": " + all[n]+"\n"; } $("#times").text(s); }); 访问原始MeasureTime对象以获得编辑时间。

答案 3 :(得分:0)

您可以在this fiddle找到我尝试过的内容。 对我而言,要点是你一次又一次地加起来,因为最初的时间并没有改变,而且你不止一次地增加了回答时间。

 <form name="frmHTML" method="post" action="">
        <table id="tables" class="form" style="width:100%">
        <tr> 

<td>Game ID</td> 
<td><input type="text"
required autocomplete="off" 
value= "<?php echo (isset($ID))?$ID:'';?>"
name="gameID"
id="gameID"
placeholder= "Enter A Number between 1 and 8"
style="width:80%"/></td>
</tr>

<tr>    
<td></td>
<td><input type="submit"
value= "Search For Game"
name= "FindDetails"
id= "FindDetails"
style= "width:80%" /></td>
</tr>

<tr>
<td>Game Name</td>
<td><input type= "text"
value = "<?php echo (isset($GameName))?$GameName:'';?>"
name="GameName"
id= "GameName"
readonly
style "width:80%" /></td>
</tr>

<tr>
<td>Game Rental Cost(per day)</td>
<td><input type= "text"
value = "<?php echo (isset($GameCost))?$GameCost:'';?>"
name="gameCost"
id="gameCost"
readonly
style= "width:80%" /></td>
</tr>

<tr>
<td>Number of days</td>
<td><input type= "text"
name="days"
id="days"
placeholder="Enter the number of days you wish to borrow the game for"
onkeyup = "mycalculate()"
autocomplete="off"
style="width:80%" /></td>
</tr>

<tr>
<td>Total Cost</td>
<td><input type="text"
value=""
name="total"
id= "total"
readonly
style="width:80%"/></td>
</tr>

<tr>
<td>Your Name</td>
<td><input type="text"
value=""
name="StudentName"
id="StudentName"
autocomplete="off"
style="width:80%"/></td>
</tr>

<tr>
<td>Date Start(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReservationStart"
id="ReservationStart"
onkeyup = "myReturnDate()"
autocomplete="off"
style="width:80%"/></td>
</tr>         


<tr>
<td>Date End(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReturnDate"
id="ReturnDate"
style="width:80%"/></td>
</tr>

<tr>    
<td></td>
<td><input type="submit"
value= "Book Game Now"
name= "Submit"
id= "Submit"
style= "width:80%" /></td>
</tr>
</table>
</form>

我将回答时间存储在一个变量中,并添加到if (name in times) { console.log('exists'); times[name] = times[name] + (b - a); //here you already had added (b1 - a) with b1 < b //either you reset 'a' here or you store the diff in a variable and sum it up at the end } else { times[name] = b - a; } 上的数组中,并尝试尽可能与原始方法保持一致。

但是我还有几件事我想念。其中主要与作弊有关。据我所知,您只想计算实际更改时间(从blur到最后focus,例如,不计算从上一个inputinput的时间绝对不是看页面的时间,也许不是在wordpad环境中写答案。)

在一个公平和安全的系统中,恕我直言,你应该考虑一个人可以看到测验的时间,而不是他/她实际写答案的时间。但这显然取决于测验的内容!

相关问题