简体   繁体   English

根据元素的类别显示工具提示文本

[英]Show tooltip text according to an element's class

I have some words wrapped inside span element with class "tooltipX", where "X" is a number. 我在类“ tooltipX”的span元素内包裹了一些单词,其中“ X”是一个数字。 The number grows with an array "Data" which holds description for the tooltip. 数字随数组“ Data”一起增长,该数组包含工具提示的描述。 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 的jsfiddle

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. 另外,使用data-*属性存储要用于工具提示的Data的索引。 So, change your HTML to follow this: 因此,更改您的HTML以遵循以下步骤:

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

(obviously changing the data-tooltip-index value per span) (显然更改每个跨度的data-tooltip-index值)

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. 另外,您可以传递函数 ,而不是将字符串传递给content ,而是让它动态返回所需Data中的特定项目。 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 . 在此函数中,您将获得元素的data-tooltip-index值(使用this ),并从Data获得相应的数组值。 So, change your JavaScript to this: 因此,将您的JavaScript更改为此:

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

DEMO DEMO


References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM