我有一个包含多个输入和选择的简单测验表单,我需要测量参赛者编写/选择答案所花费的时间。
这就是我正在尝试的,但它报告的时间不正确:
$('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>
最佳答案
在与您(OP)交谈后,我对您的基本代码进行了一些调整。
首先,.on('input ...')
每次表单元素获得焦点时都会被调用,因此事件处理程序会堆积起来。对应.off('input ...')
在模糊处理程序中调用以处理此问题。
接下来,要在 JavaScript 中创建关联数组,我们通常使用对象,所以我创建了 times = {}
.
接下来,times[name] = times[name] + (b - a);
继续使用来自 a
的初始时间值当元素第一次被聚焦时,所以聚合时间很快就会累积起来。我们可以通过设置 a = b;
来弥补这一点之后。
最后,为了跟踪选择何时更改,就像输入更改时一样,我们可以更新内部选择值,如 a_value = b_value;
when the selection has changed.
希望这就是您要找的。p>
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);
});
<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>
关于javascript - 测量输入时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417554/