在函数中使用查询到的json数据

发布于 2024-09-01 12:50:19 字数 852 浏览 4 评论 0原文

我有一个与此类似的代码:

$.ajax({
        success: function(data) {
            text = '';
            for (var i = 0; i< data.length; i++) {
                text = text + '<a href="#" id="Data_'+ i +'">' + data[i].Name + "</a><br />";
            }            
            $("#SomeId").html(text);

            for (var i = 0; i< data.length; i++) {
                $("#Data_"+i).click(function() {
                    alert(data[i]);
                    RunFunction(data[i]);
                    return false;
                });                
            }
        }
    });

它获取 json 格式的一些数据的数组,然后迭代该数组,为每个条目生成一个链接。现在我想为每个链接添加一个函数,该函数将运行一个对该数据执行某些操作的函数。问题是,在调用ajax success函数后,数据似乎不可用(尽管我认为它们的行为就像闭包)。稍后使用查询到的 json 数据的最佳方式是什么? (我认为将其设置为全局变量可以完成这项工作,但我想避免这种情况,主要是因为这个 ajax 请求可能会被多次调用)

谢谢。

I have a code similar to this:

$.ajax({
        success: function(data) {
            text = '';
            for (var i = 0; i< data.length; i++) {
                text = text + '<a href="#" id="Data_'+ i +'">' + data[i].Name + "</a><br />";
            }            
            $("#SomeId").html(text);

            for (var i = 0; i< data.length; i++) {
                $("#Data_"+i).click(function() {
                    alert(data[i]);
                    RunFunction(data[i]);
                    return false;
                });                
            }
        }
    });

This gets an array of some data in json format, then iterates through this array generating a link for each entry. Now I want to add a function for each link that will run a function that does something with this data. The problem is that the data seems to be unavailable after the ajax success function is called (although I thought that they behave like closures). What is the best way to use the queried json data later on? (I think setting it as a global variable would do the job, but I want to avoid that, mainly because this ajax request might be called multiple times)

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

方觉久 2024-09-08 12:50:20

您的问题是 i 变量由回调共享。

因此,所有回调都在最后一项上运行。

最简单的解决方案是使用 $.each

$.each(data, function(i) {
  $("#Data_" + i).click(function() {
    alert(data[i]);
    RunFunction(data[i]);
    return false;
  });
});

这将为每次迭代进行单独的函数调用,因此每次迭代都会有一个单独的 i 变量(或者在本例中为参数)。

Your problem is that the i variable is shared by the callbacks.

Therefore, all of the callbacks run on the last item.

The simplest solution is to use $.each:

$.each(data, function(i) {
  $("#Data_" + i).click(function() {
    alert(data[i]);
    RunFunction(data[i]);
    return false;
  });
});

This will make a separate function call for each iteration, so there will be a separate i variable (or, in this case, parameter) for each iteration.

oО清风挽发oО 2024-09-08 12:50:20

您可以直接使用 .bind() 并传递数据:

for (var i = 0; i< data.length; i++) {
    $("#Data_"+i).bind('click', {data: data[i]}, function() {
         alert(event.data.data);
          RunFunction(event.data.data);
          return false;
    });                
 }

我认为您犯了一个经典错误,试图在循环中生成函数。变量 i 对于所有函数都具有相同的值,但在循环结束时它甚至不再是有效的数组索引。

另请参阅 JavaScript 闭包傻瓜书(无意冒犯),示例 5。

You can use .bind() directly and passing the data:

for (var i = 0; i< data.length; i++) {
    $("#Data_"+i).bind('click', {data: data[i]}, function() {
         alert(event.data.data);
          RunFunction(event.data.data);
          return false;
    });                
 }

I think you made a classical mistake, trying to generate functions in a loop. The variable i will have the same value for all functions but it is not even a valid array index anymore at the end of the loop.

See also JavaScript Closures for Dummies (no offense), example 5.

永言不败 2024-09-08 12:50:20

SLAks 的回答很好,但他未能解释为什么它不起作用。

问题是由于范围界定造成的。试试这个:

var logger = function(x){
  console.log(x);
};
for(var j = 0; j < 10; j++){
  window.setTimeout(function(){
    logger(j);
  }, 1000);
}

那个漂亮的小函数只打印出...9!这是因为对 j 的引用由超时保留,因此到超时运行时,j 已设置为 9。

与之对比的是:

var logger = function(x){
  console.log(x);
};
for(var j = 0; j < 10; j++){
  // we're wrapping our call in an anonymous function
  // don't do this in production code...make the function external instead
  // so you don't create 10 functions
  (function(k){
    window.setTimeout(function(){
      logger(k);
    }, 1000);
  })(j);
}

此版本将内部调用包装在一个匿名函数中,该函数接受作为参数索引。由于 k 的范围现在仅限于该函数,因此记录器将按您的预期工作。

SLaks answer is a good one, but he failed to explain why it wasn't working.

The problem is due to scoping. Try this out:

var logger = function(x){
  console.log(x);
};
for(var j = 0; j < 10; j++){
  window.setTimeout(function(){
    logger(j);
  }, 1000);
}

That nice little function prints out nothing but...9s! That's because the reference to j is kept by the timeout, so by the time the timeout runs, j is already set to 9.

Contrast that with:

var logger = function(x){
  console.log(x);
};
for(var j = 0; j < 10; j++){
  // we're wrapping our call in an anonymous function
  // don't do this in production code...make the function external instead
  // so you don't create 10 functions
  (function(k){
    window.setTimeout(function(){
      logger(k);
    }, 1000);
  })(j);
}

This version wraps the inner call in an anonymous function that takes as an argument the index. Since the scope of k is now limited to that function, the logger works as you'd expect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文