Pergunta

I'm not sure what I'm doing wrong here. I want to use some data-* attribute as content for jQuery UI tooltip.

I've look at several examples in this answers:

but I can't make it work properly...

Here's my code:

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;
}
Foi útil?

Solução

I got your back dude. In your code, this was referring to the clicked div, not the tooltips.

In this corrected jsfiddle, I'm iterating over each tooltip, so that this will refer to the current tooltip: http://jsfiddle.net/P2XhC/1/

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

Outras dicas

Use jQuery .each() to iterate over each tooltip, so that this will refer to current tooltip. Try this:

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

DEMO

EDIT:

In this context:

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

'this' is actually '#btn_tooltip', changing it to a function returning the value you need will change the 'this' to be what your looking for:

$("#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: '*'
    });
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top