【问题标题】:JavaScript onKeyUp closures with timeout带有超时的 JavaScript onKeyUp 闭包
【发布时间】:2012-05-14 18:29:12
【问题描述】:

我正在尝试使用闭包将 onKeyUp 事件分配给表单中的所有输入。数组fields 包含需要分配事件的字段的所有名称。数组 ajaxFields 包含需要 ajax 验证的字段名称(来自数组 fields)。

function createEvents(fields,ajaxFields) {
    for(var x=0;x<fields.length;x++) {

        $('input[name='+fields[x]+']').keyup(function(field) { 
        //assign an onKeyUp event
            return function() {
                //some code using variable 'field' and array 'ajaxFields'
        }(fields[x]));
    }
}

我希望 onKeyUp 函数在用户完成输入该字段后的一秒钟内执行,每次按键启动时都会插入 (onKeyUp)。这将节省大量的处理空间,更不用说 ajax 调用了。到目前为止我正在使用这个:

clearTimeout(timer);
timer = setTimeout('validate()' ,1000);

您可能已经注意到函数 validate() 不存在,那是因为我不知道如何将闭包包装在命名函数中,我什至不确定我是否应该...

那我该怎么做呢?

编辑:这是当前的fiddle

【问题讨论】:

    标签: javascript timeout closures


    【解决方案1】:

    您可以(并且应该)将函数传递给setTimeout 而不是字符串。

    clearTimeout(timer);
    timer = setTimeout(function(){
        // your code here
    }, 1000);
    

    所以,在您的 keyup 中,尝试这样的操作:

    $('input[name='+fields[x]+']').keyup(function(field) { 
    //assign an onKeyUp event
        return function() {
            var that = this,
                $this = $(this);
            clearTimeout($this.data('timeout'));
            $this.data('timeout', setTimeout(function(){
                //some code using variable 'field' and array 'ajaxFields'
                // "this" will not be your element in here, make sure to use "that" (or "$this")
            }, 1000));
        };
    }(fields[x]));
    

    我将超时时间保存在$this.data,这样每个元素都可以有自己的超时时间,而不是使用全局变量。

    更新的演示:http://jsfiddle.net/Z43Bq/3/

    【讨论】:

    • 感谢您的回答,您能说明如何将其与闭包结合起来吗?
    • 我不知道为什么,但它不起作用。而且我认为您错过了结束} 对吗?
    • @webdeskil:是的,我错过了}
    • 还是不行,我在原帖里加了个jsfiddle,也许会有帮助。
    • 看来我刚刚错过了)。似乎对我有用:jsfiddle.net/Z43Bq/2
    【解决方案2】:

    你的代码应该是这样的:

    var timer;
    
    $(document).ready(function() {
        var fields = $('.field');
        var ajaxFields = $('.ajax-field');
    
        createEvents(fields, ajaxFields);
    });
    
    function createEvents(fields,ajaxFields) {
        // Use jQuery's "foreach" method
        $(fields).each(function(inx, field) {
            // Bind the listener here
            $(field).keyup(function(ev) {
                // Clear timeout if necessary
                if (timer != null) clearTimeout(timer);
    
                // Set the timeout
                timer = setTimeout(function() {
                    // Your code should here
    
                    console.log('Fields: ', fields, '\nAjax Fields: ', ajaxFields, '\nTHE field: ', field);
                }, 1000);
            });
        });
    }
    

    还可以查看工作代码的小提琴:http://jsfiddle.net/BLyhE/

    【讨论】:

    • 这似乎不起作用,请查看我在原帖中的小提琴
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2011-10-08
    • 1970-01-01
    • 2018-07-19
    • 2020-04-22
    • 1970-01-01
    • 2011-07-22
    相关资源
    最近更新 更多