代码之家  ›  专栏  ›  技术社区  ›  Evg

jQuery Ajax工具提示

  •  2
  • Evg  · 技术社区  · 15 年前

    我尝试通过这个jquery插件执行Ajax工具提示: http://jquery.bassistance.de/tooltip/demo/

    我有这样的东西:

    <p id="foottip">
      <span href="/last_votes/6">footnote</span>.
    </p>
    
    <script type="text/javascript">
      $(function() {
        $("#foottip span").tooltip({
          bodyHandler: function() {
            //dj ajax here and cache
            var tip = ''
            var url = $(this).attr("href");
    
            $.ajax({
              url:url, success:function(html){tip = html;}, async:false
            });
    
            return tip
          },
    
          showURL: false
        });
      })
    </script>   
    

    我使用异步Ajax请求来实现,但解决方案有问题,有时它会重定向页面。好像是个虫子。如何对异步请求执行Ajax工具提示?我找不到异步将结果传递给工具提示的方法。

    2 回复  |  直到 13 年前
        1
  •  3
  •   klenwell Edo    13 年前

    我碰到了同样的问题。发现了一个聪明的技巧 here 它动态地在BodyHandler回调中创建一个元素,然后在Ajax调用中更新该元素,以整齐地实现所需的效果。

    适用于上述问题:

    $("#foottip span").tooltip({
        bodyHandler: function() {
            var url = $(this).attr("href");
            var tip = $("<span/>").html("loading tip...");
    
            $.ajax({
                url: url,
                success: function(html){ tip.html(html); }
            });
    
            return tip;
        },
        showURL: false
    });
    
        2
  •  2
  •   Daniel Vassallo    15 年前

    是的,您的代码不会以异步方式工作:

    var tip = ''
    var url = $(this).attr("href");
    $.ajax({
        url:url, success:function(html){tip = html;}, async:true
    });
    
    // -- The problem here is that your bodyHandler function will return
    // -- immediately, before the AJAX callback is called.
    return tip
    

    要解决此问题,可能需要将工具提示呈现代码放入 success 您的回拨 $.ajax 请求。