在jQuery Validation插件的错误模板中插入元素 [英] Inserting an element within jQuery Validation plugin's error template
问题描述
我将 jQuery验证插件用于我的表单.它使您可以更改 errorElement 并使用 wrapper 选项包装errorElement.但是,我想像这样在之内 errorElement插入一个元素:
I'm utilizing the jQuery Validation plugin for my form. It lets you change the errorElement and wrap the errorElement using with the wrapper option. But, I want to insert an element within errorElement like this:
<label class="error"><em></em>Error message goes here</label>
是否有一种简单的方法来完成 em 标签的插入?
Is there an easy way to accomplish inserting the em tag?
我已经尝试使用errorPlacement选项(请参见下文)在em标记前添加前缀,但似乎此后插件将替换errorElement的内容.
I've tried prepending the em tag using the errorPlacement option (see below), but it seems the plugin is replacing the contents of errorElement afterwards.
$.validator.setDefaults({
errorPlacement: function(error, element) {
error.prepend('<em/>');
error.insertBefore(element);
}
});
我还尝试了使用showErrors选项(请参见下文)在em标签之前添加标签.再次,看来该插件随后将替换errorElement的内容.
I've also tried prepending the em tag using the showErrors option (see below). Again, it seems the plugin is replacing the contents of errorElement afterwards.
$.validator.setDefaults({
showErrors: function(errorMap, errorList) {
for (var i = 0; i < errorList.length; i++) {
var error = errorList[i],
$label = this.errorsFor(error.element),
$element = $(error.element);
if ($label.length && $label.find('em').length == 0) {
$label.prepend('<em/>');
}
}
this.defaultShowErrors();
}
});
我还尝试过修改插件,以便在生成错误元素时,< em>标签是前置的.直到我将注意力集中在有错误的表单元素上,然后删除 em 标记,该命令才起作用. (这样做是因为jQuery验证在我关注和/或键入字段时不断更新error元素的内容,因此删除了在错误元素创建时添加的 em 标签.) >
I've also tried modifying the plugin so that when the error element is generated, the <em> tag is prepended. That works until I focus on a form element that has an error, after which the em tag is removed. (It's doing this because jQuery validation is constantly updating the contents of the error element as I focus and/or type in the field, therefore erasing my em tag added at error-element creation.)
推荐答案
您可以使用showErrors
函数来自定义错误的显示方式:
You could use the showErrors
function to customize how errors are shown:
$.validator.setDefaults({
showErrors: function(errorMap, errorList) {
if (errorList.length < 1) {
// clear the error if validation succeeded
$('label.error').remove();
return;
}
$.each(errorList, function(index, error) {
$(error.element).next('label.error').remove();
$(error.element).after(
$('<label/>')
.addClass('error')
.append($('<em/>').text('this is some em'))
.append(error.message)
);
});
}
});
您可以在此处查看其运行情况.
这篇关于在jQuery Validation插件的错误模板中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!