0

当用户未在表单字段中输入有效数据时,我有一个表单会在 HTML 标签中显示错误消息。标签显示在表单域 onBlur 下方并一直停留在那里,直到将数据输入到表单域中。我希望标签仅在用户单击返回表单字段时显示,而不是持续显示。下面是我试图将错误标签隐藏为表单字段之外的用户选项卡的脚本。我想一旦我可以有效地隐藏它,我会担心让它再次出现。

这是HTML:

  <div class="field">
     <input type="text" name="firstname" id="firstname" class="error has-error">
     <label for="firstname" class="error">First Name is required.</label>
  </div>

还有剧本

<script type="text/javascript">
    if($('.fieldset #firstname').hasClass('error')) {
    $(this).blur($('.field label')).hide();
     }
</script>
4

2 回答 2

0

You need to pass a function into the .blur() function as a callback, something like this:

$(".fieldset #firstname").blur(function(evt) {
    if($(this).hasClass('error')) {
        $(".field label", $(this).parent()).hide();
    }
});

Note that I am doing a .field label selector within the context of the parent() of the $(this). $(this) will refer to #firstname, so if you get the parent, you can easily select within that node tree and not accidentally get some other .field label in your page.

于 2013-08-28T18:50:26.120 回答
0

You need to put the if condition inside the on blur handler.

$('.fieldset #firstname').blur(function(){
    if ($(this).hasClass('error')){
        $('.field label')).hide();
    }
})
于 2013-08-28T18:52:33.120 回答