JQuery UI 工具提示:每个工具提示有不同的图像

JQuery UI Tooltip: Have different image per tooltip

我是 JavaScript 的新手,如果这是一个愚蠢的问题,请原谅。

我正在尝试为每个工具提示显示不同的图像。 JQuery UI 已经设置好了,所以里面的文字就是图片的名称。

在下面查看我的代码:

HTML:

<div id="tooltip" class="option-child"><a id="ceramic-pro-rain" title="The Title" data-geo="Rochester" href="#" >• 1 layer of Rain on all windows and glass</a></div>

JavaScript

 <script type="text/javascript">
   $(function() {
      $( document ).tooltip({
        //items: "a, [data-geo], [title]",
        items: "a",
        position: {
          my: "left center-29",
          at: "right+10 center+18"
        },
        content: function() {

                var element = $( this );

                if ( element.is( "[data-geo]" ) ) {
                  var text = element.text();
                  return "<img class='map' alt='" + text +
                    "' src='http://www.sample.com/img/tooltip/" +
                    text + ".jpg" + "'>";
                }

                if ( element.is( "[title]" ) ) {
                  return element.attr( "title" );
                }

                if ( element.is( "img" ) ) {
                  return element.attr( "alt" );
                }
          }
      });
    });

由于您的工具提示选择器是 items: "a",因此将永远不会执行以下语句。

if ( element.is( "img" ) ) {
    return element.attr( "alt" );
}

解法:

如果你想将工具提示添加到所有 aimg 标签,有或没有 [data-geo] 试试下面的 js。

$(document).tooltip({
    items: "a,img",
    position: {
        my: "left center-29",
        at: "right+10 center+18"
    },
    content: function() {
        var element = $( this );
        if(element.is( "[data-geo]" )){
            return '<img class="map" alt="'+ $(this).data('geo') +'"  src="http://lorempixel.com/image_output/'+ $(this).data('geo') +'.jpg" />';
        }

        if ( element.is( "[title]" ) ) {
            return element.attr( "title" );
        }

        if ( element.is( "img" ) ) {
            return element.attr( "alt" );
        }
    }
});

我还添加了 html 以涵盖所有可能的变体。

<div id="tooltip" class="option-child">
    <a id="ceramic-pro-rain" title="The Title" data-geo="Rochester" href="#" >• 1 layer of Rain on all windows and glass</a>
    <img src="http://lorempixel.com/400/200/sports/" alt="sports image">
</div>
<a id="ceramic-pro-rain" title="The Title" href="#" >• Link without data-geo</a>

jsfiddle link