根据元素的类别显示工具提示文本 [英] Show tooltip text according to an element's class
问题描述
我在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
});
推荐答案
您可以扩展类并选择所有类,而不是使用特定的类.此外,使用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屋!