0

这似乎是简单的逻辑事情,但有些我无法弄清楚。我已经落后了 2 个多小时,但似乎没有任何效果。我正在做表单验证。在提交表单时,我检查字段是否为空。如果为空,我会在字段中添加一个类,使其变为红色,然后创建一个新 div 并显示错误消息。我对此有几个问题。我正在 IE8 中进行测试,而 addClass 无法在其中工作。下面是代码片段

var first =  true;
if(first == true){
$('#submit_form .required').filter(':visible').each(function() {
    var input = $(this);
    if($(this).is(':empty')){
        $(this).css("border","1px solid #FF0004");
        //$(this).addClass("highlight");
        $(this).after('<div class="error_text">Required</div>');
        first = false;
        return false;
    }else{
        return true;
    }
});
}
else{
  $('#submit_form .required').filter(':visible').each(function() {
    var input = $(this);
    if($(this).is(':empty')){
        $(this).css("border","1px solid #FF0004");
        //$(this).addClass("highlight");
                  //I ned to remove the Required text here or else it will get added twice.
        $(this).after('');
                  //Add the text here
                    $(this).after('<div class="error_text">Required</div>');
        return false;
    }else{
        return true;
    }
});
}

因此,当用户第一次单击提交按钮时,first = true,它会验证哪个字段为空,它也会显示红色边框和文本。这工作正常。现在当用户填写一些字段并再次输入提交时,还有一些未填写的必填字段。所以现在我希望填写的字段删除边框和必填文本,然后显示红色和必填字段现在是空的。我尝试了很多东西,我对此感到厌烦。不知何故,我对此没有正确的逻辑。那里的一些人可以帮助我吗?我不想使用验证插件。

4

1 回答 1

1

当出现时,<div>您要删除的是您正在检查的元素之后的下一个元素(this引用的那个),因此您应该能够这样做来删除它:

$(this).next('div.error_text').remove();

顺便说一句,如果你想从你的函数返回一个值,它应该只是return trueor return false,使用等号 ( =) 是不正确的。

first逻辑似乎没有必要,因为 jQuery 擅长处理元素不存在的情况。您可以将整个代码简化为:

var returnValue = true;
$('#submit_form .required').filter(':visible').each(function () {
    var input = $(this);
    input.next('div.error_text').remove();
    input.removeClass('highlight');
    if (input.is(':empty')) {
        input.addClass('highlight');
        input.after('<div class="error_text">Required</div>');
        returnValue = false;
    }
});
return returnValue;

然后是该类的以下CSS highlight

.highlight {
    border: 1px solid #ff0004;
}

请注意,在上面我使用了一个returnValue变量。那是因为你有一个匿名函数被传递给.each(),并且在里面调用return false只会结束循环的执行,它不会阻止你的表单被提交。

于 2013-10-11T09:55:18.873 回答