JavaScript onKeyUp闭包超时 [英] JavaScript onKeyUp closures with timeout
问题描述
我试图使用闭包将onKeyUp事件分配给表单中的所有输入。数组 fields
包含需要分配给它们的事件的字段的所有名称。数组 ajaxFields
包含需要ajax验证的字段名称(来自数组 fields
)。
function createEvents(fields,ajaxFields){
for(var x = 0; x< fields.length; x ++){
$('input [name ='+ fields [x] +']')keyup(function(field){
//分配一个onKeyUp事件
return function {
//一些代码使用变量'field'和数组'ajaxFields'
}(fields [x]));
}
}
我希望onKeyUp函数在用户完成在该字段中输入之后,每次该键被启动(onKeyUp)。这将节省大量的处理空间,更不用说ajax调用。到目前为止im使用这个:
clearTimeout(timer);
timer = setTimeout('validate()',1000);您可能已经注意到函数 validate()$ c $ 不存在,这是因为我不知道如何包装一个命名的函数内的闭包,甚至不知道我是否应该...
:这里是目前的 fiddle 解决方案 )传递函数到 setTimeout
而不是字符串。
clearTimeout ;
timer = setTimeout(function(){
//您的代码在这里
},1000);
因此,在 keyup
像这样:
$('input [name ='+ fields [x] +'字段){
//分配一个onKeyUp事件
返回函数(){
var that = this,
$ this = $(this);
clearTimeout this.data('timeout'));
$ this.data('timeout',setTimeout(function(){
// some code using variable'field'and array'ajaxFields'
//this不会是你的元素,请务必使用that(或$ this)
},1000));
};
} fields [x]));
我在 $ this.data中保存超时
更新的演示: http://jsfiddle.net/Z43Bq/3/
Im trying to assign an onKeyUp event to all inputs within a form, using closures. the array fields
contains all the names of the fields that require the event assigned to them. The array ajaxFields
contains the names of the fields (from the array fields
) that requires ajax validation.
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]));
}
}
I would like the onKeyUp function to be executed a second after the user has finished typing in that field, insted of every time the key is up (onKeyUp). this would save up a lot of processing space, not to mention the ajax calls. So far im using this:
clearTimeout(timer);
timer = setTimeout('validate()' ,1000);
You might have noticed that the function validate()
doesn't exist, and thats because I dont know how to wrap the closures inside a named function, and im not even sure if I should...
So how do I do that?
EDIT: here is a current fiddle
解决方案 You can (and should) pass functions to setTimeout
instead of strings.
clearTimeout(timer);
timer = setTimeout(function(){
// your code here
}, 1000);
So, in your keyup
, try something like this:
$('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]));
I save the timeout in $this.data
, so that each element can have its own timeout, instead of using a global variable.
Updated Demo: http://jsfiddle.net/Z43Bq/3/
这篇关于JavaScript onKeyUp闭包超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!