最近几天我一直在研究刺激演示功能。现在是需要调整的细节,特别是我坚持这个: 我希望我的按键事件只执行 20 次,之后会出现一个警告,表明任务已结束。我试过循环和一段时间。我可能已经忘记了概览以查看我的错误,但我的代码在 20 次按键后并没有停止。我的错误在哪里?
var i=0;
while (i < 20) {
$(function(){
$(document).keypress(function(e){
if ($(e.target).is('input, textarea')) {
return;
};
if (e.which === 97 || e.which === 108 || e.which === 32) {
if(Math.random() < 0.5) {
var new_word = stim[Math.floor((Math.random()*stim.length)+1)].name;
$("#abc").text(new_word);
} else {
var new_img = stim[Math.floor((Math.random()*stim.length)+1)].path;
$("#abc").empty();
var prox_img = $('<img id="abcimg" height="300px" width="300px">');
prox_img.attr('src', new_img);
prox_img.appendTo('#abc');
}
};
});
});
i++;
alert("abcdefg");
};
最佳答案
你不需要循环,只需要使用全局计数器,例如i
var i = 0; // saves count of keypress events
$(function() {
$(document).keypress(function(e) {
if ($(e.target).is('input, textarea') || i > 20) { // check for 20 events
return;
};
i++; // increase counter...
if (e.which === 97 || e.which === 108 || e.which === 32) {
if(Math.random() < 0.5) {
var new_word = stim[Math.floor((Math.random()*stim.length)+1)].name;
$("#abc").text(new_word);
} else {
var new_img = stim[Math.floor((Math.random()*stim.length)+1)].path;
$("#abc").empty();
var prox_img = $('<img id="abcimg" height="300px" width="300px">');
prox_img.attr('src', new_img);
prox_img.appendTo('#abc');
}
}
});
});
关于javascript - 如何限制查询函数在循环时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22430562/