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

why is myvar undefined after myvar = $(this)

本文关键字:myvar 之后 定义 为什么 this      更新时间:2023-09-26

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

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" }
});
}

由于td.well不止一个,因此您必须迭代它们以设置正确的well$

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"
            }
        });
    });
}

$(this) instace不是指$("#water-table tbody td.well") .所以你需要把它改成$("#water-table tbody td.well")的本能,如下所示,

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" }
});
}

希望这对你有帮助。