2013-01-25 11 views
0

jQuery $.post 함수를 호출하는 이벤트가 있습니다. $.post 함수 안에 정의 된 변수에 액세스하고 싶습니다. 문제가 있습니다.

이 경우 currentId 변수에 액세스하고 싶습니다.

$('.notMatching').click(function(){  
    var currentId = this.id; 
    $.post("http://"+ document.domain + baseUrl +"/tables/demo.json", { id: this.id }, 
      function(dat){ 

       alert(currentId); //undefined 

       if(dat['result']==1){ 
        $(this).parent().html('<input type="checkbox" class="first" value="'+this.id+'">'); 
       } 
      } 
    ); 
}); 

할 방법이 있습니까?

Btw,이 이벤트는 $(document).ready(function(){ 안에 있으며 다른 많은 이벤트가 있습니다.

+0

http://remysharp.com/2007/04/12/jquerys-this-demystified/ –

답변

3

당신은 글로벌 아무것도하여 어떤 임무를 수행 할 필요가 없습니다 ...

$('.notMatching').click(function(){  

    var that = this 
    $.post("http://"+ document.domain + baseUrl +"/tables/demo.json", { id: this.id }, 
      function(dat){ 

       alert(that.id); 

       if(dat['result']==1){ 
        $(this).parent().html('<input type="checkbox" class="first" value="'+that.id+'">'); 
       } 
      } 
    ); 
}); 

그것을 보존 할 필요가 변수를 that으로 변경하면 성공 후 다시 액세스 할 수 있습니다. $.post

+0

이것이 전역 변수 옵션을 선언하는 것보다 낫다고 생각합니까? – Alvaro

+0

예 :) ... 저는 개인적으로 awesomeness의'전역 적 피하기'운동의 팬입니다 ... :) – AdityaParab

+0

그냥 팁 : 전역 사용을 피하고 콜백 함수를 사용합니다 ... :) – AdityaParab

1

전역 적으로 변수를 선언하십시오.

var currentId = null; 
$('.notMatching').click(function() { 
currentId = this.id; 
$.post("http://" + document.domain + baseUrl + "/tables/demo.json", { 
    id : this.id 
}, function(dat) { 

    alert(currentId); 
    //undefined 

    if (dat['result'] == 1) { 
     $(this).parent().html('<input type="checkbox" class="first" value="' + this.id + '">'); 
    } 
}); 

});

콜백 내부의 범위가 변경
+0

JavaScript 응용 프로그램에서 전역 변수 선언을 피하는 것이 가장 좋습니다. –

1

, 당신은 당신의 this 지정

$('.notMatching').click(function(){  
    var currentId = this.id; 
    var that = this; 
    if (currentId) 
     $.post("http://"+ document.domain + baseUrl +"/tables/demo.json", { id: currentId }, function(dat){ 
      if(dat['result']==1) 
       $(that).parent().html('<input type="checkbox" class="first" value="'+currentId+'">'); 
     }); 
    else 
     alert('No Id'); 
}); 
1
var currentId = null; 
var that = this; 
$('.notMatching').click(function() { 
currentId = this.id; 
$.ajax({ 
    'type' : 'POST', 
    'dataType' : 'JSON', 
    'data': {'id':currentId}, 
    'url': "http://" + document.domain + baseUrl + "/tables/demo.json", 
    'success': function(response){ 
    if ((JSON.parse(response)).result === 1) { 
     $(this).parent().html('<input type="checkbox" class="first" value="' + that.id + '">'); 
    } 
    } 
}); 
관련 문제