此答案中包含 Tooltipster 版本 2.1、3.0 和 4.0 的解决方案。
注意,在下面的示例中,.tooltipster() 仅附加到 type="text" input 元素。如果您的form 包含其他类型的数据输入元素,例如type="radio"、type="date"、textarea、select 等,那么您必须相应地调整您的选择器或创建额外的这些其他元素的 .tooltipster() 实例。否则,一切都会失败并出现错误。
工具提示器 v2.1
首先,在 all 将显示错误的特定 form 元素上初始化 Tooltipster 插件 (with any options):
$(document).ready(function () {
// initialize tooltipster on form input elements
$('#myform input[type="text"]').tooltipster({
trigger: 'custom', // default is 'hover' which is no good here
onlyOne: false, // allow multiple tips to be open at a time
position: 'right' // display the tips to the right of the element
});
});
其次,使用Tooltipster's advanced options和success: and errorPlacement: callback functions built into the Validate plugin自动显示和隐藏工具提示如下:
$(document).ready(function () {
// initialize validate plugin on the form
$('#myform').validate({
// any other options & rules,
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
success: function (label, element) {
$(element).tooltipster('hide');
}
});
});
工作演示:http://jsfiddle.net/2DUX2
编辑:更新代码以利用 2013 年 2 月 12 日在 2.1 版中发布的新 Tooltipster API 功能
Tooltipster v3.0 更新
Tooltipster 3.0 已经发布,因此与上面所示的工作方式不同。以下代码提供了一个更新的示例。此版本还有一个额外的好处,即当消息尚未更改时,不会在每次击键时调用 Tooltipster。
(不要忘记,您仍然需要将.tooltipster() 附加到相关的input 元素,如上图所示。)
$(document).ready(function () {
// initialize validate plugin on the form
$('#myform').validate({
// any other options & rules,
errorPlacement: function (error, element) {
var lastError = $(element).data('lastError'),
newError = $(error).text();
$(element).data('lastError', newError);
if(newError !== '' && newError !== lastError){
$(element).tooltipster('content', newError);
$(element).tooltipster('show');
}
},
success: function (label, element) {
$(element).tooltipster('hide');
}
});
});
使用 Tooltipster v3.0 的演示:jsfiddle.net/2DUX2/3/
Tooltipster v4.0 更新
请注意,onlyOne 选项已从 Tooltipster 插件的 4.0 版本中删除。
我还将success 回调替换为unhighlight。在“可选”字段上,当该字段随后被空白时,错误消息从未被删除......这是因为success 函数在这些情况下不会触发。此问题并非孤立于 Tooltipster 版本 4,但以下代码将继续解决此问题。
// initialize Tooltipster on text input elements
$('input[type="text"]').tooltipster({ //find more options on the tooltipster page
trigger: 'custom', // default is 'hover' which is no good here
position: 'top',
animation: 'grow'
});
// initialize jQuery Validate
$("#myform").validate({
errorPlacement: function (error, element) {
var ele = $(element),
err = $(error),
msg = err.text();
if (msg != null && msg !== '') {
ele.tooltipster('content', msg);
ele.tooltipster('open');
}
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
},
rules: {
....
使用 Tooltipster v4.0 的演示:https://jsfiddle.net/h5grrrr9/