【发布时间】:2013-08-12 11:57:11
【问题描述】:
当一个元素被点击时这个函数被调用。它根据单击的元素创建一个字符串,然后在 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(json[object]); 之前alert(option),我会收到一个简单地说“成功”的警报。不知道这是怎么回事。 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"
}
【问题讨论】:
-
可以发一下Messages.json的内容吗?查看 JSON 的结构有助于了解发生了什么。
-
没问题。大功告成。
-
alert(option);显示“成功”的原因是因为您已将其重新定义为回调的第二个参数:, function(json, option) {。要么不包含它(因为我认为你不需要它),要么更改参数名称 -
我尝试更改参数名称。那似乎没有任何作用。我还尝试只传入一个类似 function(json, "Space Control") { 的字符串,这似乎破坏了一切,并引发了“Unexpected String”错误。
-
@CaptainStack 不能使用字符串作为参数名称。回调不需要第二个参数,所以只需使用
, function(json) {。然后,alert(option);确保设置正确。如果它看起来正确但不起作用,请尝试修剪它
标签: javascript jquery json scope