dongsanhu4784 2015-06-30 12:28
浏览 19

使用循环显示一系列数字,按键盘键时退出

I want to hits a to display series of numbers using loop (like i am using 1 to 10000) and it will stop dispalying the numbers when someone hits specific key for example: Press A

I have used following code but not working:

for($i=0;$i<10000;$i++){
    echo $i."<br/>";
}

and js code is:

$(document).keypress(function(e) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == 13){
        setTimeout('window.stop()',6000);
    }
});

How can i do it? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • duangan7834 2015-06-30 12:46
    关注

    Your JavaScript can't stop the PHP code. PHP is executed, the response is sent to browser, browser parses the page and then your JavaScript is executed. You could use the setInterval function for setting an interval and stop it on the keypress event.

    var i = 0;
    var intId = setInterval(function() {
        if ( i === 10000 ) {
          stopInterval();
        }
        i++;
        // ...
    }, 2);
    
    function stopInterval() {
       clearInterval(intId);
    }
    
    window.addEventListener('keypress', function(event) {
       if ( event.which === 13 ) stopInterval();
    });
    

    Here is a demo.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向