2013-03-26 81 views
0

工作后,我不得不做出简单的验证。如果按F5然​​后代码将无法正常工作刷新页面,它正在对第一次,但填补文本值后的罚款。.blur不是页面加载

步骤,以产生错误上第一文本框和模糊

  1. 焦点无填充的任何值。功能会提醒“错误”,并命名类错误会增加在文本框中

  2. 现在将在文本框,然后按F5值。然后从文本框中删除值和模糊功能将提醒'没有错误'这里是问题。它应该警告,因为我们在空白文本框上模糊。

我投入了门,发现了这个问题,因为的onload功能存在的,我提到的代码,如果输入的文本值不等于空,则模糊文本框中

<head> 
    <script type="text/javascript" src="jquery-1.8.3.js"></script> 
    <script type="text/javascript"> 
    $(function(){ 
     $('input').blur(function(){ 
      if($(this).hasClass('error')){ 
      alert('error') 
      } 
      else { 
      alert('no error') 
     } 
    }) 
    }) 

    function test(id){ 
    if($(id).val()==''){ 
     $(id).addClass('error') 
    } 
    else { 
     $(id).removeClass('error') 
    } 
    } 

    $(function(){ 
    setTimeout(function(){ 
      $('input').each(function(){ 
      if($(this).val()!=''){ 
       $(this).blur(); 
      } 
      }) 
    },1000) 
    }) 
</script> 
<style> 
    .error{ border:#F00 solid 1px} 
</style> 
</head> 


<body> 
    <input type="text" onblur="test(this)"/> 
    <input type="text" onblur="test(this)" /> 
</body> 
+0

其中prowser和jQuery的版本是您使用? – 2013-03-26 08:47:57

+0

我使用实际上是在第一次测试1.8.3版本和Mozilla Firefox – Carlos 2013-03-26 08:48:21

+0

()函数执行第一,但页面上刷新.blur函数执行第一 – Carlos 2013-03-26 08:54:29

回答

0

这将是你更好在确定输入框是否为空时检查值,而不是css类。

$('input').blur(function() { 
    if ($.trim($(this).val()) == '') { 
     alert('error') 
    } else { 
     alert('no error') 
    } 
}); 

我认为FF试图保存HTML文档的状态,所以这个类仍然应用于该元素

0

只是尝试用下面的:

脚本部分:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script type="text/javascript"> 
    function test(textId){  
    if($("#"+textId).val()==""){ 
     $("#"+textId).addClass("error"); 
     alert("Error"); 
     setTimeout(function(){ 
     $("#"+textId).focus(); 
     },100); 
     return false; 
    } 
    else { 
     $("#"+textId).removeClass("error"); 
     alert("No Error"); 
     return true; 
    } 
    } 
    </script> 

HTML部分:

<style> 
    .error{ border:#F00 solid 1px} 
</style> 
<body> 
    <input type="text" onblur="test(this.id);" id="text1" value=""/> 
    <input type="text" onblur="test(this.id);" id="text2" value=""/> 
</body> 

我认为这可以帮助你解决你的问题。