2013-08-30 4 views
0

내가 뭘 잘못하고 있니? div의 텍스트를 동적으로 변경하고이 div에 CSS 클래스를 추가/삭제하고 싶습니다. ' 이 같은 이름을 가진 몇 div의 ID는 다르게jQuery가 CSS/텍스트를 동적으로 변경합니다.

<div class="mydiv" id="1">Text</div> 
<div class="mydiv" id="2">Text</div> 
<div class="mydiv" id="3">Text</div> 

<input type="hidden" name="myfield" id="myfield" value="myvalue" /> 

나는 스프링 MVC 컨트롤러에 아약스 게시물을 전송하고 완벽하게 답변 (데이터) 참 또는 거짓 얻고있다. 하지만 처음에는 모든 값 $ (". mydiv"). attr ("id")을 생성하고이 성공 이후에는 this.id가 변경되지 않은 것을 볼 수 있습니다. 이 문제를 어떻게 해결할 수 있습니까? 루프로 시작하는 여러 문제, 아약스 성공의 실행 컨텍스트가있는 것처럼

$(document).ready(function() { 
    $.each($('.mydiv'), function() { 
     var code = $(".mydiv").attr("id"); 

     $.ajax({ 
      url: '/mycontroller', 
      type: 'POST', 
      dataType: 'json', 
      data: { 
       id: $("#myfield").attr("value"), 
       codeId: this.id 
      }, 
      success: function (data) { 
       if (data == false) { 
        $("#" + this.id).addClass("myNewClass"); 
        $("#" + this.id).text("FirstText"); 
       } else { 
        $("#" + this.id).removeClass("myNewClass"); 
        $("#" + this.id).text("SecondText"); 
       } 
      } 
     }); 
    }); 
}); 

답변

0

시도

콜백 등이

$(document).ready(function() { 
    $('.mydiv').each(function() { 
     //use this.id to get the current elements id - $(".mydiv").attr("id") will give the id of first element with class mydiv 
     var code = this.id; 

     $.ajax({ 
      url: '/mycontroller', 
      type: 'POST', 
      dataType: 'json', 
      data: { 
       id: $("#myfield").attr("value"), 
       codeId: this.id 
      }, 
      success: $.proxy(function (data) { 
       //inside the callback this was not pointing the element, here a proxy based soution is used 
       //another solution is to assign var self = this; before the ajax request and then instead of this inside the function use self 
       if (data == false) { 
        $(this).addClass("myNewClass"); 
        $(this).text("FirstText"); 
       } else { 
        $(this).removeClass("myNewClass"); 
        $(this).text("SecondText"); 
       } 
      }, this) 
     }); 
    }); 
}); 
0

.html() 대신 .text()

의 시도 같은데
관련 문제