jQuery-验证错误标签模板

jQuery-validation errorlabel template

我正在尝试使用此模板包装错误标签,但没有成功。 (http://jqueryvalidation.org/)

<div class="alert alert-error">
    <div class="fx-alert-icon">
        <i class="fxicons fxicons-error"></i>
    </div>
    <div class="fx-alert-desc">
        <label id="input-error" class="has-error" for="input1">
            Input with error!!
        </label>
    </div>
</div>

一个解决方案是更改 errorElement,然后在方法 showErrors() 中更改 message,但我对这个解决方案感到不舒服...

var errMsgTmpl = '<div class="alert alert-error">' +
                 '<div class="fx-alert-icon">' +
                 ' <i class="fxicons fxicons-error"></i>' +
                 '</div>' +
                 '<div class="fx-alert-desc"><label for="{{LABEL-FOR}}">{{ERROR-MSG}}</label></div>' +
                 '</div>';

$.validator.setDefaults({            
    errorElement: "section", 
    showErrors: function (errorMap, errorList) {
        var i, elements;
        for (i = 0; errorList[i]; i++) {
            errorList[i].message = errMsgTmpl
            .replace(/{{ERROR-MSG}}/, errorList[i].message)
            .replace(/{{LABEL-FOR}}/, $(errorList[i].element).attr('id'));
        }
        this.defaultShowErrors();
    }
});

目前我的布局没有模板,只使用 css,但在某些时候我的信息可能会更复杂,我认为使用模板是最好的选择。

I'm trying to wrap the error label with this template, but without success.

您不会将元素包装在模板中。您可以将此结构放入页面中,然后使用插件将错误消息元素动态插入其中。

你没有说明你希望这个新结构出现在 input 的什么地方,所以我无法计算出正确的 DOM 遍历技术。默认 label 元素放置在 之后 input

无论如何,您将应用各种 jQuery DOM 遍历方法,例如 .parents().closest().siblings().next() 等。到 element 对象以将 <label> 元素(error 对象)准确地注入到您想要的结构中。

$.validator.setDefaults({
    errorPlacement: function(error, element) {
        error.insertAfter(element);
    }
});