2016-10-08 3 views
0

정보를 동적으로 채우는 루프가 있습니다.jQuery에서 클래스 내부 요소를 선택하는 방법은 무엇입니까?

<div class="main"> 

<div class="more"> 
    more 
</div> 
<span></span> 
    .... 
<div class="more"> 
    more 
</div> 
<span></span> 

</div> 

클릭하면 특정 div가 표시됩니다. "ajax"를 호출합니다. 성공하면 해당 div의 내용과 다음 내용을 일부 내용으로 대체하려고합니다.

$(document).on("click", ".more", function (event) { 
      $.ajax({ 
       url: '..', 
       datatype: 'application/json', 
       success: function (data) { 
        $(".more",this).html("Update Dev"); //update div 
        $(".more",this).find('span:first').text("Update Span"); //update span 
       }, 
       error: function() { alert('something bad happened'); } 
      }); 
     }); 

클릭 한 요소에 어떻게 액세스합니까?

감사

+0

$ (필요한 사항) –

+0

사용 event.target – user3599803

+0

중복에 대한 http://stackoverflow.com/questions/2643798/how-to-access-the-this-inside-ajax-success-callback-function –

답변

2

당신은 클릭 버튼을 얻을 클릭 핸들러 내부 $(this)를 사용할 수 있습니다. AJAX 콜백이 아닌 클릭 핸들러에서 캡쳐해야합니다.

$(document).on("click", ".more", function (event) { 
    var clickedDiv = $(this); // <- capture clicked div to variable 

    $.ajax({ 
     url: '..', 
     datatype: 'application/json', 
     success: function (data) { 
      // use captured div to set the contents 
      clickedDiv.html("Update Dev"); 
      // use captured div and function next() to get the span element 
      clickedDiv.next('span').html("Updated span"); // then update span 
     }, 
     error: function() { alert('something bad happened'); } 
    }); 
}); 
+0

설명해 주셔서 감사합니다. 범위가 업데이트되지 않습니다. 나는'clickedDiv.next ('span') .html ("Updated span");에 의해 수정되었고 효과가있었습니다. – Ben

+0

@Ben 네, 맞습니다. div의 selector를 복사했는데'span'에는'more' 클래스가 없다는 것을 알지 못했습니다. 나는 대답을 – dotnetom

+0

업데이트했습니다. div를 변경할 때 예를 들어 .animate를 쉽게 추가 할 수 있는지 궁금합니다. 나는 내 질문에 구체적으로 언급하지 않았다는 것을 알고있다. – Ben

관련 문제