带有JSON对象的JavaScript范围

时间:2013-08-10 19:18:57

标签: javascript jquery json scope

单击元素时会调用此函数。它根据单击的元素创建一个字符串,然后在JSON对象中查找与该字符串关联的值。然后它会提醒该值。这是它的外观:

function alertHelp(){
    var option = $(this).context.parentNode.textContent.substring(0, $(this).context.parentNode.textContent.length - 2);
    $.getJSON("Messages.json", function(json, option) {
        alert(json[option]);
    });
}

我发现该选项设置正确,但是当传递给该功能时,警报会被更改。如果我在alert(option)之前alert(json[object]);,我会收到一条简单说“成功”的提醒。不确定是什么。 alert(json[option])只是提醒“未定义”。

这是Messages.json:

{
    "Space Control": "Red = a square black controls. Green = a square white controls. Yellow = a square contested by both players",
    "Legal Moves": "Click on a piece and a blue dot will appear on all the squares that piece can move to",
    "PieceFlair": "When you move a piece, all the pieces that come under attack as a direct result of the piece you moved will pulse white",
    "Forks": "All the moves that would result in a simultaneous attack of two pieces are shown",
    "Pins": "Not yet implemented"
}

1 个答案:

答案 0 :(得分:2)

您已var option function参数option“隐藏”了var text = $(this).context.parentNode.textContent; var option = text.substring(0, text.length - 2); $.getJSON("Messages.json", function(json, status) { alert(status); // success alert(json[option]); }); ,请尝试以下方式:

{{1}}