2014-01-13 187 views
0

每次有一个'required'类的字段被更改时,我想设置一个超时。 我原来的脚本有一个错误,如果在超时完成之前移动到另一个具有相同类的字段,它将重置它,并且只在最后一个字段执行该功能。 为了解决这个问题,我想添加特定字段的名称到定时器功能。但是,我的下面的尝试不起作用。我在想,如果每个领域都有计时器,它应该工作。 首先,我的方法是否正确?如果是的话,我在做什么错了?如果不是,我该如何实现自己的目标?用另一个变量内容创建一个变量名称

$('.required', this).bind('keyup change',function() { 
    var fieldName = $(this).attr('name'); 
    var timer[fieldName] = null; 
    clearTimeout(timer[fieldName]); 
    timer[fieldName] = setTimeout(
     function() { 
      if(!$(this).val()) { 
       $(this).nextAll('.required-prompt').first().remove(); 
       $(this).after(prompt); 
      } else { 
       $(this).nextAll('.required-prompt').first().remove(); 
       required = true; 
      } 
     } 
     , 2000 
    ); 
}); 
+0

不是timer这里未定义或正在其他地方宣布它? –

+0

@ A.Wolff定时器在上面第3行定义,所以它的范围在函数中。 –

+1

@JeremyMiller不,它不是!顺便说一句,这是无效的语法,使用var –

回答

3

代码应该是这样的:

var timer = {}; 
$('.required', this).bind('keyup change',function() { 
    var fieldName = $(this).attr('name'); 
    clearTimeout(timer[fieldName]); 
    timer[fieldName] = setTimeout(
     function() { 
      if(!$(this).val()) { 
       $(this).nextAll('.required-prompt').first().remove(); 
       $(this).after(prompt); 
      } else { 
       $(this).nextAll('.required-prompt').first().remove(); 
       required = true; 
      } 
     } 
     , 2000 
    ); 
}); 
+0

嗨。谢谢。我已经尝试过,但它在jQuery库中提供'TypeError:f.nodeName的错误是未定义的'。有任何想法吗? – user2889310

+0

您的FIELD作为名称属性?提供相关的HTML代码和jsfiddle怎么样?! –

+0

我自己修复了。谢谢。 – user2889310

相关问题