2014-04-26 33 views
0

我不知道我在这里做错了什么。我想用一些data-*属性作为jQuery UI工具提示的内容。使用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; 
} 
+0

我看到提示,当我将鼠标悬停在他们。这里有什么问题? – swajak

+0

@swajak这是一个经过编码的内容,从上面的行中删除注释,以便将文本属性作为文本使用 –

回答

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"), 
.. 

“这个”其实是“#btn_tooltip”,将其更改为一个函数返回你需要将改变“这”是什么你的价值寻找:

$("#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: '*' 
    }); 
}); 
+0

看看这个https://api.jquery.com/data/ –

+0

我的不好,我以为你在用一个老版本的jQuery和我的代码错误使它工作。我会编辑我的回答 – mambrow

1

使用jQuery .each()遍历每个提示,让this将参考目前的工具提示。试试这个:

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

DEMO

+0

挨打你一分钟!兄弟抱歉。无论如何,请有一个upvote。 – swajak

+1

@swajak:没有问题。在这里学习和贡献:) – Unknown