How can i refer the object on jQuery?

2019-07-16 15:03发布

问题:

I'm making a script which has one ajax call inside an each function. The problem is that on the success callback from ajax call, I want to use the object that we are using at each function.

EDIT: Here is some of my code:

configs={
  general:{
    max_ads:6},
  logs:{
    selector:"div#MicrodualGetAd-debug"},
  connection:{
    type:"POST",
    url:"http://www.microdual.com/api/microdualgetad",
    cache:false,
    timeout:20000,
    dataType:"json",
    data:{
      adget_id:null,
      adget_session:null,
      client_action:null},
    error:function(r,s,e){
      MicrodualGetAdLog("Ajax-Error: "+s+"\n");
    }
  }
};


$("div.MicrodualGetAd").each(function(){
  configs.connection.data.adget_id = $(this).attr("rel");
  configs.connection.data.client_action = "view";
  configs.connection.data.success = function(d,s,r){
    $(this).hide();
    alert("'OK'");
    if(d.hackattemp.status){
      MicrodualGetAdLog("MicrodualGetAd-Error: "+d.hackattemp.msg+"\n");
      $(this).append(d.hackattemp.msg);
    }
  }
  $.ajax(configs.connection);
});

回答1:

You need to save the value of this just inside your each callback.

$("#hello").each(function() {
    var that = this;

    $.ajax({
        url: "www.mysite.com/mypage",
        success: function(d) {
            hello.call(that);
        }
    });
})​

Also, you should check the value of d differently; either

if (typeof d === 'undefined' && d !== '') ...

or simply

if (d) ...

Edit 1: This should work, assuming the only problem you're having is getting the right value of this:

$("div.MicrodualGetAd").each(function() {
    var $this = $(this);
    configs.connection.data.adget_id = $this.attr("rel");
    configs.connection.data.client_action = "view";
    configs.connection.data.success = function(d, s, r) {
        $this.hide();
        alert("'OK'");
        if (d.hackattemp.status) {
            MicrodualGetAdLog("MicrodualGetAd-Error: " + d.hackattemp.msg + "\n");
            $this.append(d.hackattemp.msg);
        }
    }
    $.ajax(configs.connection);
});​