【问题标题】:jquery how to pass variable from the last iteration?jquery如何从最后一次迭代中传递变量?
【发布时间】:2012-06-01 12:25:30
【问题描述】:

我有一个通过对象的每个循环,

在其中,我创建了一些图像,我想在其中放入对上次迭代中图像的引用的数据。

例如:

.each((function(some_data){ return function(i, obj){

    var prev='???'; // how do I retrieve the value from the last cycle?
    var image=new Image();
        image.data('prev',prev);
        prev=image;
                // how do I pass the value to next cycle?
    }})(some_data));

【问题讨论】:

  • 把你的 prev 定义放到 each 块之外。
  • 哦,我从来没想过……但这听起来是个好主意!

标签: javascript jquery image recursion iteration


【解决方案1】:

在您的 .each 调用之前,您在外部范围中定义变量..

var prev=null;
collection.each(function(idx, val){
   alert("Prev should have value from previous iteration (or null):" + prev);
   var image=new Image();
   image.data('prev',prev);
   prev=image;
 })(some_data));

【讨论】:

  • 我也可以不使用 return function() 从 each 中传递 i 和 obj 变量吗?
  • 是的,我认为不需要函数包装器。如果您必须等待图像在此循环中加载,那么事情会变得更加困难。
【解决方案2】:

在 jquery 的每个范围之外使用一个全局值。

myloopingvar=null;

 .each((function(some_data){ return function(i, obj){

if(loopingvar !=null) 
 {// do stuff
 }
 var image=new Image(); image.data('prev',prev); loopingvar=image }})(some_data));

【讨论】:

  • Eww。全球的。伊克。 (当使用var 方法时,根据另一个答案,当代码希望在另一个函数中时,它不会污染window。)
  • @pst 由于全局命名空间问题,直到一个晚上的 bug 搜寻,人们才开始欣赏仔细的范围界定:p
猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
相关资源
最近更新 更多