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(){他の多くのイベントの中にあります。

4

4 に答える 4

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

于 2013-01-25T11:32:32.847 に答える
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 + '">');
    }
});

});

于 2013-01-25T11:30:01.127 に答える
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');
});
于 2013-01-25T11:30:21.130 に答える
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 + '">');
    }
  }
});
于 2013-01-25T11:43:13.850 に答える