我的 $(document).ready(...);
中有一个从服务器检索到的 json 对象它有一个字符串,我想将其解析为也在 $(document).ready(...);
中定义的函数所以,例如:
$(document).ready(function{
$.getJSON(/*blah*/,function(data){/*more blah*/});
function doAdd(left,right) {
return left+right;
}
function doSub(left,right) {
return left-right;
}
});
使用 json 字符串:
{"doAdd":{"left":10,"right":20}}
我想到的一种方法是在加载 json 之前创建函数的关联数组:
var assocArray=...;
assocArray['doAdd'] = doAdd;
assocArray['doSub'] = doSub;
使用 eval
或 window[]();
不好,因为函数可能有一段时间不会被调用,基本上我想链接/解析但还没有执行。
最佳答案
将您的 JSON 更改为
{method: "doAdd", parameters : {"left":10,"right":20}}
然后做
var method = eval(json.method);
// This doesn't call it. Just gets the pointer
或者(没试过)
var method = this[json.method]
关于javascript - 解析 $(document).ready(function(){}) 中的函数指针;通过 json 字符串名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5149352/