2013-06-22 5 views
2

내 서버로 ajax 요청을 보냅니다. 그러면 나는 물건을 받는다. 그때 나는 내 문제는 (1) 이미지 요소가 생성되고 있다는 점이다 루프for 루프 내에서 jQuery .load()

if (typeof response.payload.result == 'object') { 
    var ln = response.payload.result.length; 
    var i; 
    if (ln > 0) { 
     for (i = 0; i < ln; i++) { 
       /* this shows i was increased for every iteration */ 
       console.log(i); 
      var current_img = response.payload.result[i]; 
      var img = $("<img />").attr('src', current_img) 
      .load(function() { 
        console.log(i); 
        /* this logs the last iteration 4 times */ 
       $("#product-images").append(img); 
      }); 
     } 
    } 
} 

의를 사용하여 객체를 통과

{ 
    "payload": { 
     "result": [ 
      "http://example.com/img1.jpg", 
      "http://example.com/img2.jpg", 
      "http://example.com/img3.jpg", 
      "http://example.com/img4.jpg", 
      "http://example.com/img5.jpg" 
     ] 
    } 
} 

: 개체가 좋아하는이 보인다. 이 코드가 실행 된 후 DOM에 추가되는 단일 요소는 배열의 마지막 요소 값입니다. jQuery.load()이 마지막 반복에서만 호출되는 이유는 무엇입니까?

답변

2
if (typeof response.payload.result == 'object') { 
    var ln = response.payload.result.length; 
    var i; 
    if (ln > 0) { 
     for (i = 0; i < ln; i++) { 
      (function (n) { 
       var current_img = response.payload.result[i]; 
       var img = $("<img />").attr('src', current_img) 
        .load(function() { 
        console.log(n); 
        $("#product-images").append(img); 
       }); 
      })(i); 
     } 
    } 
} 
+0

내 문제가 해결되었습니다. ' –

0

나는 u는이 라인

var img = $("<img />").attr('src', current_img) 

에 대한 세미콜론을 놓친 당신은 당신이 이미지를로드하려는 요소의 선택을 지정하지 않은 것 같아요.

+0

아니요. 요소에 점 표기법을 사용하고 있습니다. –

+0

오크 .. 알았어. :) – Kelsadita

관련 문제