【问题标题】:Use data-* attribute as tooltip for jQuery UI使用 data-* 属性作为 jQuery UI 的工具提示
【发布时间】:2014-04-26 00:46:36
【问题描述】:

我不确定我在这里做错了什么。我想使用一些 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;
}

【问题讨论】:

  • 当我将鼠标悬停在工具提示上时会看到它们。这里有什么问题?
  • @swajak 这是一个硬编码的内容,请从上面的行中删除注释以便将数据属性用作文本

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


【解决方案1】:

我得到了你的背,伙计。在您的代码中,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: '*'
        })
    });
});

【讨论】:

  • 我怎么错过了!非常感谢!
【解决方案2】:

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

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

DEMO

【讨论】:

  • 领先你一分钟!兄弟抱歉。无论如何都要投赞成票。
【解决方案3】:

编辑:

在这种情况下:

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

“this”实际上是“#btn_tooltip”,将其更改为返回所需值的函数会将“this”更改为您要查找的内容:

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

【讨论】:

  • 我的错,我以为您使用的是旧版本的 jQuery,而我的代码错误使它起作用。我会编辑我的答案
猜你喜欢
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
  • 2015-12-07
  • 2014-06-23
  • 1970-01-01
相关资源
最近更新 更多