jQuery 验证插件:向元素的错误容器添加/删除类
我正在使用 jQuery 验证插件,并编写了以下代码,该代码将一个类添加到元素的 () 父级 (
) if无效,以及在
之前插入实际错误元素 ()。
HTML……
<label>
text<br><input>
</label>
和jQuery。
$("#form_to_validate").validate({
rules: {
...
},
errorElement: "span",
errorPlacement: function(error, element) {
element.parent().addClass('error');
error.insertBefore(element.parent().children("br"));
}
});
因此,如果表单元素未验证,它会变成:
<label class="error">
text<span>error text</span><br><input>
</label>
这很有效,但是,如果字段的内容被更正并变得有效,则该类显然不会从其父级中删除(实际上,错误元素也不会被删除) ,相反,它只获取 display: none;
CSS 属性)。如何检查元素是否有效并删除其父类(如果有效)?
任何帮助将不胜感激!
编辑:添加了更多信息。
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>
.
the HTML ...
<label>
text<br><input>
</label>
... and the 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 ?
Any help would be greatly appreciated !
Edited: Added more information.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过一番更深入的挖掘后,我发现答案就在我眼皮子底下,但不幸的是,对我来说,答案隐藏得很好。插件内置高亮功能(惊喜,惊喜)。通常它会突出显示/取消突出显示该元素,但它可以轻松转换为在该元素的父元素上工作:
我希望这会对某人有所帮助!
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:
I hope this will help someone !
errorElement: 'none'
对我有用。errorElement: 'none'
worked for me.