2013-01-25 53 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+'">'); 
       } 
      } 
    ); 
}); 

有沒有辦法做到這一點?

順便說一下,這個事件在$(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+'">'); 
       } 
      } 
    ); 
}); 

將您的this變量爲that和你的那個將成功訪問回撥$.post

+0

您是否認爲這比聲明全局變量選項更好? – Alvaro

+0

是:)...我個人很喜歡'避免全球化運動的迷人... :) – 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

回調內部的範圍發生變化時,你需要保留它

$('.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 + '">'); 
    } 
    } 
});