Javascript 内部函数无法访问匿名函数参数

Javascript 内部函数无法访问匿名函数参数,javascript,scope,anonymous-function,Javascript,Scope,Anonymous Function,我一直在努力做到这一点 function test() { $.getJSON("http://myurl.com",function (data){ for( i=0; i<data.length; i++){ test = createElement('img'); test.onclick = function (){ myotherfun(data[i]); } } } } funct

我一直在努力做到这一点

function test()
{
    $.getJSON("http://myurl.com",function (data){
        for( i=0; i<data.length; i++){
            test = createElement('img');
            test.onclick = function (){ myotherfun(data[i]); }
        }
    }
}

function myotherfun(data)
{
    alert(data);
}
功能测试()
{
$.getJSON(“http://myurl.com,函数(数据){

对于(i=0;i现在您已经编辑了您的问题,我可以看到问题XD

问题是,
onclick
函数将使用
data
和(更重要的是)
i
的当前值。因此本质上它是在寻找
data[data.length]
,而根据
length
的定义,这是不存在的

相反,您需要“锁定”迭代器的值

for(i=0; i<data.length; i++) {
  (function(i) {
    // do stuff that relies on i
  })(i);
}

用于(i=0;属性名是
onclick
而不是
onclick
。JavaSscript与HTML不同,区分大小写。此外,您必须将元素附加到DOM中,并让它实际加载一个图像。没有
onclick
属性。您真正的代码看起来像什么?错误实际上是怎么说的?我猜它没有使用单词“scope”。是的,我将重新编辑代码。但问题不在于onclick是否工作。web控制台显示“data[i]未定义“我假设它是系统函数的变量范围。@user2022595:是的,我知道它与onclick无关。重点是提供准确的信息。@系统非常感谢。我的第一篇文章我的不好。会很快学会的!:)或只是
test.onclick=myotherfun.bind($,data[i])
这很有魅力!谢谢你的快速回复。我应该试着调查一下,而不是浪费你的时间:)