javascript - 如何限制查询函数在循环时运行?

标签 javascript jquery function loops

最近几天我一直在研究刺激演示功能。现在是需要调整的细节,特别是我坚持这个: 我希望我的按键事件只执行 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/

相关文章:

javascript - 无法让 SVG 正确缩放

javascript - JS删除div内容并编写新代码

c 函数调用

c - 一种奇怪的函数定义方式

javascript - 单击链接,概述按钮,直到单击其他地方

javascript - 在 d3 堆积面积图的工具提示中显示未选定路径的值?

javascript - meteor : Not being able to hide UI elements

c - 具有指向指针和 strcpy 的指针的函数

javascript - 理解 typescript 中的构造函数接口(interface)

javascript - 如何将数据从 Javascript 传递到 PHP Laravel?