jQuery验证更改元素背景颜色

8

默认情况下,jQuery.validate似乎不会更改无效元素的背景颜色。是否还可以更改,但我需要一个指示元素的背景颜色,但它从未恢复到先前的样式:

 $('form[name="register"]').validate({
        errorClass: 'jqInvalid',
        rules: {
            fnameCreate: "required", //input
            monthCreate: "required", //select
            emailCreate: { required: true, email: true }, //input
            passwordCreate: "required", //input type=password
        },
        messages: {
            fnameCreate: "",
            monthCreate: "",
            emailCreate: "",
            passwordCreate: "",
        },
        errorPlacement: function (error, element) {
            element.css('background', '#ffdddd');
        }
    });

编辑(示例)

<div class="field">
  <div class="labelName_fb">
    <label for="email">Email</label>
  </div>
  <div class="divforText3">
    <div class="divLeft"></div>
    <div class="textbox-image3">
      <input class="txt required" id="emailCreate" name="emailCreate" value="" maxlength="100" type="text"  style='width:180px'>
    </div>
    <div class="divright"></div>
  </div>
</div>

当输入元素在错误时被赋予了 jqInvalid 错误类。

CSS

/* line 3 */ .error { background: #ffdddd; } /* I have since removed the errorClass option */
/* line 254 */ .field .txt {background:transparent none repeat scroll 0 0;border:medium none;color:#000;font-size:11px;width:130px; margin:5px 0;}

CSS screenshot in Chrome

2个回答

6
无效元素默认会被赋予一个名为error的类(默认情况下),或者在您的情况下是jqInvalid,因为您已经设置了errorClass选项,只需在样式表中对该类进行自定义样式即可,例如:
.jqInvalid { background: #ffdddd; }

你可以覆盖错误消息的具体设置(默认元素为<label>),如果需要的话:
label.jqInvalid { background: none; }

这种CSS方法可以处理删除操作...因为一旦该类被验证,它就会被移除。如果您想要将绿色背景应用于有效元素等,则还有一个“success”类。

我移除了errorClass和errorPlacement选项,然后我注意到.error类被添加到元素中。但是,我的CSS无法覆盖它。在Firebug中,CSS存在(在活动CSS下面),但被划掉了。 - David Fox
这是一个类规则 .field .txt,其中 .field 是包裹盒子的 div,.txt 直接应用。如果 class 属性为 class="txt jqInvalid",我认为 .txt.jqInvalid(或错误)样式都会被应用? - David Fox
我已经尝试过在Firebug提到的那一行之前和之后各加一行代码,但无论如何都被覆盖了。 - David Fox
@David - 你有个示例页面吗?我可以快速查看一下......你的覆盖样式或者后声明或更具体(总是获胜)。 - Nick Craver
我添加了我认为相关的CSS和行号。Firebug没有提到除了计算出来的element.style { width: 180px;}之外的任何其他CSS,它出现在.field .txt样式上方。 - David Fox
显示剩余4条评论

2
这是一个特定性问题。 .error.jqInvalid 都比 .field .txt 不够具体。
因此,增加特定性需要将CSS更改为.field input.error,它的权重比.field .txt更高,所以顺序不再重要。
有关特定性的信息,请参见此处

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接