0
 $(".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());在成功函数中返回空输出?

4

3 回答 3

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", ...).

于 2013-10-29T06:39:43.127 回答
0

在成功函数中,this 指的是调用 $.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 
  });
于 2013-10-29T06:43:02.393 回答
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 相关的回调的上下文。

于 2013-10-29T06:46:56.507 回答