开发者

function inside javascript loop

I'm having trouble understanding this problem. I'm assuming its a scope issue, but I don't know how to get around it.

I created an array to store the x and y positions of 6 separate elements

var pos = new Array();
for(i=1;i<7;i++){
    pos['box'+i] = $('.box'+i).position();
}

I would like to then add this to each element with another loop

for(i=1;i<7;i++){
    $('.box'+i).draggable({zIndex: 9999, revert: function(){
        $(this).animate({top:pos['box'+i].top, left:pos['box'开发者_StackOverflow中文版+i].left}, 500, "easeOutElastic");
    }});
}

The dragging works, but the revert function doesn't. With some alerts I found that it is trying to get the position of pos['box7'] which doesn't exist. Why isn't it adding each 'box'+i ?


Try to encapsulate the code inside the loop in a new "context":

(function(i) {
  .. your code
})(i);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜