2012-11-08 4 views
0

창로드시 이미지가 이미 저장되어 있는지 확인하려고합니다. 그렇다면 HTML을 변경하여 저장하는 링크가 비활성화되도록하십시오. 이 코드 종류는 .each()없이 작동하지만 첫 번째 태그 만 찾아서 다른 모든 유사한 태그를 변경합니다. 물론 각 태그를 개별적으로 수행하고 싶습니다. 파이어 버그의 포스트 트랜잭션을 살펴보면 각 Ajax 호출이 제대로 처리되고 올바른 href 값이 전송되지만 html 업데이트가 적용되지 않는 것으로 보입니다. if 문은해야 할 때 경고 메시지가 나타나기 때문에 실패하지 않습니다. $(this)이 항목 값을 검색하는 데 왜 작동하지만 html 변경을 설정할 때 작동하지 않는지 알고 싶습니다.jQuery. each() 일부 변경 사항이 html로 작성되지 않았습니다.

window.onload = function() { 
    $(".img a").each(function() { 
     var item=$(this).attr('href'); 
     var action="check"; 
     jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) { 
      var result=data.result; 
      if (result=="saved") { 
       $(this).html("<div style='line-height:4em '>Saved</div>"); 
       $(this).attr("href","saved"); 
       alert(result); 
      } 

     }, "json") 
     .error(function() {   
      alert("error: unable to contact web service"); 
     }); 
    }); 
} 
+0

당신이 JS를 제공 할 수 코드 실패를 보여주는 바이올린? –

답변

2

문제는 콜백 내부의 this 당신이 생각하는 요소를 참조하지 않습니다.

아약스 전에 해당 요소에 대한 참조를 만들어 사용해야합니다.

window.onload = function() { 
    $(".img a").each(function() { 
     var self = $(this), 
      item = this.href, 
      action = "check"; 
     jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) { 
      var result=data.result; 
      if (result=="saved") { 
       self.html("<div style='line-height:4em '>Saved</div>"); 
       self.attr("href","saved"); 
       alert(result); 
      } 

     }, "json") 
     .error(function() {   
      alert("error: unable to contact web service"); 
     }); 
    }); 
} 

또한이 비슷한 일을 확인하기 위해 많은 Ajax 호출을 실행하는 잔인한처럼 보인다.
코드를 리팩터링하여 단일 아약스 호출을 만들지 만 파일 목록을 전달하여 확인하고 모든 이미지를 참조하는 응답을 처리하십시오 (하나씩)

+0

예, 감사합니다. 나는이 한 번의 전화를하기를 기대할 것이다. 그러나 그것은 꽤 빠르다. – Codeguy007

1

자바 스크립트 클로저에는 몇 가지 규칙이 있습니다. 다른 closure에서 this은 다른 참조입니다.

모든 곳에서 u는 성공의 방법의 호출자가 <a> 요소하지

1

필요

var that = $(this); 

시도하고 항목이 타이밍 that를 사용합니다.

window.onload = function() { 
$(".img a").each(function() { 
    var $this = $(this); 
    var item=$(this).attr('href'); 
    var action="check"; 
    jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) { 
     var result=data.result; 
     if (result=="saved") { 
      $this.html("<div style='line-height:4em '>Saved</div>"); 
      $this.attr("href","saved"); 
      alert(result); 
     } 

    }, "json") 
    .error(function() {   
     alert("error: unable to contact web service"); 
    }); 
}); 
} 

희망이 있습니다.

1

것은 변경해보십시오 :

var item=$(this).attr('href'); 

에 : 그런 다음

var $item = $(this); 
var item=$item.attr('href'); 

변경 :

$(this).html("<div style='line-height:4em '>Saved</div>"); 
$(this).attr("href","saved"); 

사람 :

$item.html("<div style='line-height:4em '>Saved</div>"); 
$item.attr("href","saved"); 
관련 문제