jQuery UI Tooltip Widget中的AJAX内容

jQuery UI 1.9中有一个新的Tooltip Widget,其API文档提示可以在其中显示AJAX内容,但没有任何进一步的细节。 我想我可以用同步和阻塞请求来完成类似的事情,但这不是我想要的。

如何使其显示使用异步AJAX请求检索的任何内容?

这是我的博客中的 jqueryui tootip小部件的ajax示例.hope它有帮助。

$(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'); }); } }); 

小提琴

使用工具提示“内容”选项将“AJAX”文本放入工具提示时要注意的一点是,文本检索会在工具提示初始化中引入延迟。

如果鼠标在工具提示的dom节点上快速移动,则鼠标移出事件可能在初始化完成之前发生,在这种情况下,工具提示尚未监听事件。

结果是显示工具提示,并且在鼠标移回节点并再次移出之前不会关闭工具提示。

虽然它可能会产生一些可能不需要的网络开销,但请考虑在配置工具提示之前检索工具提示文本。

在我的应用程序中,我使用自己的jquery扩展来进行AJAX调用,解析resutls并初始化所有工具提示,显然你可以使用jquery和/或你自己的扩展,但它的要点是:

使用图像标记作为工具提示锚点,要检索的文本由名称atrribute标识:

  

使用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调用和jQuery UI工具提示的示例。

HTML:

    

JavaScript的:

 // (1) Define HTML string to be echo'ed by dummy AJAX API var html_data = "I am a tooltip"; // (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上的这个例子: