这个选择器问题与ajax

时间:2013-10-29 06:34:29

标签: jquery html ajax

 $(".selectedBatch").each(function(index){

      var batchCode = $(this).text();

      //edit batch attr start 

      $.ajax({

          url: "../Controller/getBatchAttr.php",
          type: "GET",
          async: false, 
          data: "BM_Course_Code="+ batchCode,
          success:function(resBatch){
              console.log($(this).text());
              //$(this).attr("data-commence-date",resBatch.BM_Commence_Date);
              //$(this).attr("data-end-date",resBatch.BM_End_Date);
              //$(this).attr("data-ins-days",resBatch.BM_Ins_Days);
          }
      });
      //edit batch attr end 
  });

为什么console.log($(this).text());在成功函数中返回一个空输出?

3 个答案:

答案 0 :(得分:3)

this不是局部变量,因此它不会保存在闭包中。您需要为其设置一个局部变量,然后使用它:

$(".selectedBatch").each(function(index){

    var $that = $(this);
    var batchCode = $that.text();

    //edit batch attr start 

    $.ajax({

        url: "../Controller/getBatchAttr.php",
        type: "GET",
        async: false, 
        data: {BM_Course_Code: batchCode},
        success:function(resBatch){
            console.log($that.text());
            //$that.data("commence-date",resBatch.BM_Commence_Date);
            //$that.data("end-date",resBatch.BM_End_Date);
            //$that.data("ins-days",resBatch.BM_Ins_Days);
        }
    });
    //edit batch attr end 
});

我做出的其他改变:

  • 将对象作为data:选项传递。 jQuery将确保它正确地进行URL编码(您忘记调用encodeURIComponent)。

  • 而不是.attr("data-XXX", ...)我使用.data("XXX", ...)

答案 1 :(得分:0)

在成功函数中,这指的是在调用$ .ajax时创建的ajax对象。您已经为文本创建了变量。您可以使用它而不是使用$(this).text()

$(".selectedBatch").each(function(index){

      var batchCode = $(this).text();

      //edit batch attr start 

      $.ajax({

          url: "../Controller/getBatchAttr.php",
          type: "GET",
          async: false, 
          data: "BM_Course_Code="+ batchCode,
          success:function(resBatch){
              console.log(batchCode );
              //$(this).attr("data-commence-date",resBatch.BM_Commence_Date);
              //$(this).attr("data-end-date",resBatch.BM_End_Date);
              //$(this).attr("data-ins-days",resBatch.BM_Ins_Days);
          }
      });
      //edit batch attr end 
  });

答案 2 :(得分:0)

您可以在此处使用context对象,如:

$.ajax({
    url: "../Controller/getBatchAttr.php",
    type: "GET",
    async: false,
    data: "BM_Course_Code=" + batchCode,
    context: this,    // <--- using context as `this` here
    success: function (resBatch) {
        console.log($(this).text());   // Now you can use `this` here
    }
});

context对象将成为所有与Ajax相关的回调的上下文。