jQuery 验证插件:在元素的错误容器中添加/删除类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2505053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:38:36  来源:igfitidea点击:

jQuery Validation plugin: add/remove class to/from element's error container

jqueryelementhighlightingjquery-validate

提问by Valentin Flachsel

I'm working with the jQuery Validation plugin and I wrote the following code which adds a class to the element's (<input>) parent (<label>) if not valid, as well as inserting the actual error element (<span>) before the <br>.

我正在使用 jQuery Validation 插件,我编写了以下代码,如果无效,则向元素的 ( <input>) 父 ( <label>)添加一个类,并<span><br>.

the HTML ...

HTML ...

<label>
    text<br><input>
</label>

... and the jQuery.

...和jQuery。

$("#form_to_validate").validate({
    rules: {
    ...
    },
    errorElement: "span",
    errorPlacement: function(error, element) {
        element.parent().addClass('error');
        error.insertBefore(element.parent().children("br"));
    }
});

So, if a form element doesn't validate, it turns into:

所以,如果一个表单元素没有通过验证,它就会变成:

<label class="error">
    text<span>error text</span><br><input>
</label>

This works great, however, if a field's content is corrected and becomes valid, the class obviously doesn't get removed from its parent (actually, neither does the error element, instead it just gets a display: none;CSS property). How can I check if an element becomes valid and remove its parent class if so ?

这很有效,但是,如果一个字段的内容被更正并变得有效,则该类显然不会从其父项中删除(实际上,错误元素也不会,而只是获取一个display: none;CSS 属性)。如何检查元素是否有效并在有效时删除其父类?

Any help would be greatly appreciated !

任何帮助将不胜感激 !



Edited: Added more information.

编辑:添加了更多信息。

回答by Valentin Flachsel

After some more heavy digging I found the answer right under my nose, but unfortunately for me, well hidden. The plug-in has a built-in highlighting function (surprise, surprise). Normally it would highlight/unhighlight the element, but it can easily be converted to work on the element's parent:

经过一些更重的挖掘,我在我的鼻子底下找到了答案,但不幸的是,对我来说,隐藏得很好。插件内置高亮功能(惊喜,惊喜)。通常它会突出显示/取消突出显示元素,但它可以很容易地转换为在元素的父级上工作:

$("#form_to_validate").validate({
    rules: {
    ...
    },
    errorElement: "span",
    errorPlacement: function(error, element) {
        error.insertBefore(element.parent().children("br"));
    },
    highlight: function(element) {
        $(element).parent().addClass("error");
    },
    unhighlight: function(element) {
        $(element).parent().removeClass("error");
    }
});

I hope this will help someone !

我希望这会帮助某人!

回答by chris

errorElement: 'none'worked for me.

errorElement: 'none'为我工作。