首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么myvar在myvar = $(this)之后没有定义

为什么myvar在myvar = $(this)之后没有定义
EN

Stack Overflow用户
提问于 2013-09-14 20:25:03
回答 2查看 89关注 0票数 0

所以我做了一个关于沙漠中的幸存者的小游戏。幸存者在返回淘金热鬼城的路上,不得不喝散落在沙漠中的水井里的水。一些井可以喝水,但其他井是有毒的。我在一个表的TD元素上显示了一个工具提示,这些TD元素的类是"well“。在工具提示的初始化对象中,我需要获取对当前TD元素的引用,以便将其传递给设置工具提示的"content“属性的函数。在这个函数中,我必须测试当前的TD是否也有“毒化”的类。

代码语言:javascript
复制
function initWellsTooltip() {
 $("#water-table tbody td.well").tooltip({

    content: function () {           
        var well$ = $( this );  // 
        // at this point stepping through the code in the debugger,
        // well$ is undefined and I don't understand why,
        // because $(this).hasClass("poisoned") succeeds.
        // VS2010 debugger shows as follows:
        //  ?$(this).hasClass("poisoned")
        //  true
        //  ?well$
        //  'well$' is undefined
        if (well$.hasClass("poisoned")) {
              return "poisoned!";
        } else {
            return "potable";
        }

    },
    items: "td.well",
    position: { my: "left+15 center", at: "left top" }

});
}
EN

回答 2

Stack Overflow用户

发布于 2013-09-14 21:16:26

由于存在多个td.well,因此必须遍历它们以设置正确的well$

代码语言:javascript
复制
function initWellsTooltip() {
    $("#water-table tbody td.well").each(function() {
        var well$ = $(this);          

        well$.tooltip({
            content: function () {
                return well$.hasClass("poisoned") ? "poisoned!" : "potable";
            },
            items: "td.well",
            position: {
                my: "left+15 center",
                at: "left top"
            }
        });
    });
}
票数 2
EN

Stack Overflow用户

发布于 2013-09-14 20:31:24

那个时刻的$(this)并不是指$("#water-table tbody td.well")。因此您需要将其更改为$("#water-table tbody td.well")的实例,如下所示:

代码语言:javascript
复制
function initWellsTooltip() {
 var that = $("#water-table tbody td.well");
 that.tooltip({

    content: function () {           
        var well$ = that;  // 
        // at this point stepping through the code in the debugger,
        // well$ is undefined and I don't understand why,
        // because $(this).hasClass("poisoned") succeeds.
        // VS2010 debugger shows as follows:
        //  ?$(this).hasClass("poisoned")
        //  true
        //  ?well$
        //  'well$' is undefined
        if (well$.hasClass("poisoned")) {
              return "poisoned!";
        } else {
            return "potable";
        }

    },
    items: "td.well",
    position: { my: "left+15 center", at: "left top" }

});
}

希望这对你有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18801719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档