使用data- *属性作为jQuery UI的工具提示

时间:2014-04-26 00:46:36

标签: jquery jquery-ui jquery-ui-tooltip

我不确定我在这里做错了什么。我想使用一些data-*属性作为jQuery UI工具提示的内容。

我在这个答案中看了几个例子:

但我无法使其正常运作......

这是我的代码:

FIDDLE: http://jsfiddle.net/P2XhC/

HTML

<div id="div_1">number 1</div>
<div id="div_2">number 2</div>
<div id="div_3">number 3</div>

<button id="btn_class">STEP 1: Add class to 1 and 3</button>
<button id="btn_tooltip">STEP 2: Add tooltip to class</button>
<button id="btn_check">STEP 3: Check for data</button>

JS

$("#btn_class").click(function()
{
    $("#div_1, #div_3").addClass("tooltip").data("text", "show this!");
});

$("#btn_tooltip").click(function()
{
    $(".tooltip").tooltip({
        //content: $(this).data("text"), //this doesn't work
        content: "show something...", //this works!
        items: '*'
    });
});

$("#btn_check").click(function()
{
    $("div").each(function()
    {
        console.log($(this).attr("id") + " = " + $(this).data("text");
    });
});

CSS

.tooltip
{
    color: red;
}

3 个答案:

答案 0 :(得分:2)

我找到了你的后背。在您的代码中,this指的是点击的div,而不是工具提示。

在这个经过纠正的jsfiddle中,我在每个工具提示上进行迭代,以便this引用当前的工具提示:http://jsfiddle.net/P2XhC/1/

$("#btn_tooltip").click(function()
{
    $(".tooltip").each(function() {
        $(this).tooltip({
            content: $(this).data("text"),
            //content: "show something...",
            items: '*'
        })
    });
});

答案 1 :(得分:1)

修改

在此背景下:

..
content: $(this).data("text"),
..

&#39;这&#39;实际上是&#39;#btn_tooltip&#39;,将其更改为返回所需值的函数将更改&#39;这个&#39;成为你的目标:

$("#btn_class").click(function()
{
    $("#div_1, #div_3").addClass("tooltip").data("text", "show this!");
});

$("#btn_tooltip").click(function()
{
    $(".tooltip").tooltip({
        content: function() { return $(this).data("text"); },
        //content: "show something...",
        items: '*'
    });
});

答案 2 :(得分:1)

使用jQuery .each()迭代每个工具提示,以便this引用当前工具提示。试试这个:

$("#btn_tooltip").click(function()
{
    $(".tooltip").each(function() {
            $(this).tooltip({
                content: $(this).data('text'),
                items: '*'
            });
        });
});

DEMO