jQuery UI 1.9中有一个新的Tooltip窗口小部件,其API文档暗示可以在其中显示Ajax内容,但没有任何其他详细信息。我想我可以通过同步和阻止请求来完成类似的事情,但这不是我想要的。
如何使其显示使用异步AJAX请求检索的任何内容?
这是我的博客中的jqueryui tootip小部件的一个示例。
$(document).tooltip({
items:'.tooltip',
tooltipClass:'preview-tip',
position: { my: "left+15 top", at: "right center" },
content:function(callback) {
$.get('preview.php', {
id:id
}, function(data) {
callback(data); //**call the callback function to return the value**
});
},
});
这显然不是一个完整的解决方案,但它显示了在open
事件中动态获取数据的基本技术:
$('#tippy').tooltip({
content: '... waiting on ajax ...',
open: function(evt, ui) {
var elem = $(this);
$.ajax('/echo/html').always(function() {
elem.tooltip('option', 'content', 'Ajax call complete');
});
}
});
请参阅小提琴
在使用工具提示" content"选项将文本" ajax"到工具提示中时,要查找的一件事是,文本检索将延迟延迟到工具提示初始化中。
如果鼠标在工具提示-ED DOM节点上快速移动,则可能发生鼠标输出事件,在初始化完成之前,在这种情况下,工具提示尚未侦听该事件。
结果是显示了工具提示,并且直到鼠标再次移动到节点并再次向外移动之前。
。虽然它会产生可能不需要的某些网络开销,但请在配置工具提示之前检索工具提示文本。
在我的应用程序中,我使用自己的jQuery扩展名进行AJAX调用,解析重新打击并初始化所有工具提示,显然您可以使用jQuery和/或您自己的扩展名,但要点是:
使用图像标签作为工具提示锚,要检索的文本由名称trribute标识:
<img class="tooltipclassname" name="tooltipIdentifier" />
使用Invoke扩展方法配置所有工具提示:
$(".tooltipclassname").extension("tooltip");
扩展程序的工具提示方法:
var ids = "";
var nodes = this;
// Collect all tooltip identifiers into a comma separated string
this.each(function() {
ids = ids + $(this).attr("name") + ",";
});
// Use extension method to call server
$().extension("invoke",
{
// Model and method identify a server class/method to retrieve the tip texts
"model": "ToolTips",
"method": "Get",
// Send tooltipIds parameter
"parms": [ new myParmClass("tipIds", ids ) ],
// Function to call on success. data is a JSON object that my extension builds
// from the server's response
"successFn": function(msg, data) {
$(nodes).each(function(){
// Configure each tooltip:
// - set image source
// - set image title (getstring is my extension method to pull a string from the JSON object, remember that the image's name attribute identifies the text)
// - initialise the tooltip
$(this).attr("src", "images/tooltip.png")
.prop("title", $(data).extension("getstring", $(this).attr("name")))
.tooltip();
});
},
"errorFn": function(msg, data) {
// Do stuff
}
});
// Return the jquery object
return this;
这是一个使用jsfiddle的示例"/echo/html/" ajax call in a jquery ui tooltip。
html:
<body>
<input id="tooltip" title="tooltip here" value="place mouse here">
</body>
javaScript:
// (1) Define HTML string to be echo'ed by dummy AJAX API
var html_data = "<b>I am a tooltip</b>";
// (2) Attach tooltip functionality to element with id == tooltip
// (3) Bind results of AJAX call to the tooltip
// (4) Specify items: "*" because only the element with id == tooltip will be matched
$( "#tooltip" ).tooltip({
content: function( response ) {
$.ajax({
url: "/echo/html/",
data: {
'html': html_data
},
type: "POST"
})
.then(function( data ) {
response( data );
});
},
items: "*"
});
这是JSFiddle上的此示例: