根据元素的类别显示工具提示文本 [英] Show tooltip text according to an element's class

查看:105
本文介绍了根据元素的类别显示工具提示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在span元素内用"tooltipX"类包装了一些单词,其中"X"是一个数字.数字随数组"Data"一起增长,该数组保存了工具提示的描述.如何显示正确元素的描述?我希望使用类似下面的代码,但是我不知道如何循环它.

I have some words wrapped inside span element with class "tooltipX", where "X" is a number. The number grows with an array "Data" which holds description for the tooltip. How can I show the description for the right element? I hope for something like the code below, but I don't know how to loop it.

$( document ).tooltip({
items: ".tooltip"+X+"",
content: Data[X].desc
});

JSFiddle

推荐答案

您可以扩展类并选择所有类,而不是使用特定的类.此外,使用data-*属性存储Data的索引以用于工具提示.因此,更改HTML以遵循以下要求:

Instead of using specific classes, you could broaden the class and select them all. In addition, use a data-* attribute to store the index of the Data to use for the tooltip. So, change your HTML to follow this:

<span class="tooltip" data-tooltip-index="0">

(明显改变每个跨度的data-tooltip-index值)

(obviously changing the data-tooltip-index value per span)

此外,您可以传递函数,而不是将字符串传递给content,并使其动态地从Data返回所需的特定项目.每当需要显示工具提示时,就会执行此函数,并将返回值用作其内容.在此函数中,您将获取元素的data-tooltip-index值(使用this),并从Data获取相应的数组值.因此,将您的JavaScript更改为此:

Also, instead of passing a string to content, you can pass a function, and have it dynamically return the specific item from Data that you want. This function will execute every time the tooltip needs to be shown and uses the returned value as its contents. In this function, you would get the element's data-tooltip-index value (using this), and get the corresponding array value from Data. So, change your JavaScript to this:

$(document).tooltip({
    items: ".tooltip",
    content: function () {
        var index = $(this).attr("data-tooltip-index");
        return Data[index].desc;
    }
});

演示

参考:

这篇关于根据元素的类别显示工具提示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆