【问题标题】:setTimeout does not wait for specified number of millisecondssetTimeout 不等待指定的毫秒数
【发布时间】:2011-07-03 14:24:35
【问题描述】:

我希望在几秒钟不活动后触发提交(使用onKeyup 事件)。

我的代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title</title>
    </head>
    <body>
        <form id="getJSONForm">
            <textarea rows="1" cols="10" onKeyUp="onKeyUp()"></textarea>
            <input type="submit" value="Submit" id="getJSON" />
        </form>

        <div id="result"  class="functions"></div>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $.ajaxSetup ({
                cache: false
            });

            var timer;

            function onKeyUp() {
                stoper();
                timer = setTimeout ( $("#getJSONForm").submit(), 10000 ); 
            }

            function stoper() {
                clearTimeout(timer);
            }

            $("#getJSONForm").submit(function(){
                    $("#result").html("hello");
                    return false;
            });
        </script>
    </body>
</html>

但是...表单似乎会在每个onKeyUp 事件中提交。它不会等待计时器达到指定的 10,000 毫秒。 有没有办法解决这个问题?

【问题讨论】:

    标签: javascript jquery settimeout onkeyup


    【解决方案1】:

    setTimeout() 的第一个参数必须是函数对象(或字符串,但您不应该使用它)。像这样:

    timer = setTimeout(function () {
       $("#getJSONForm").submit();
    }, 10000);
    

    您当前正在将$("#getJSONForm").submit() 的值传递给setTimeout(),这可能不是您想要的。

    除此之外,我建议使用 jQuery 的事件处理而不是 HTML 参数。它更加优雅、灵活且易于维护。你可以这样做:

    $('#getJSONForm textarea').keyup(function () {
       // the content of your onKeyUp() function goes here
    });
    

    看看the API documentation关于这个话题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2021-02-26
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多